Written in the beginning

  • Before that, many of my friends had already upgradedvite, but most of them are vUE’s projects, so today we put beforewebpackthereactProject Upgrade tovite!
  • And for that, in order to keep you from stepping on holes, LET me justchina-dev.cnThe website project has been upgradedvite

  • For the online drawing function, it may not have any impact, but with online writingjavascriptThis feature has a big impact, because the library used before, will be withwebpackBinding, currently not supportedvite, so I changed the technology stack, but the effect is betterwebpackStrong binding is a false proposition, there are more ways than difficult, and build tools are just an option

PS: This site is always free, and there are a lot of front-end free learning materials, so I took this project out of the business part and made it into a simple project template

The official start of the

If you haven’t read my previous post on the core differences between WebPack and Vite, I suggest you read it first and then come back to this post

  • Migrating webpack to Vite:

    • The heelwebpackAny time there is a strong plug-in/technology stack decoupling, it is not a good thing to have a strong dependency on a third party tool/environment, as architects who have done heavy system deployments will know
    • Remove from the projectimportSo let’s replace all of them with throughimportIntroduction. You could say,esmIt’s a trend because it’s a norm.vue3No longer supportedie11It’s just a matter of time to replace the country’s old systems. It’s a big trend.Some official websites in Shenzhen are already recommending you to use the new browser
    • Standardize your code, can’t appeartypescriptType errors and other warnings,viteHot update is very fragile, it is possible that a small warning or non-standard writing will lead to hot update failure, and error positioning is not accurate, or directly not error, but failure (these pits will be described below).
  • Next, clone my scaffolding locally

    • addresshttps://github.com/JinJieTan/Peter-/tree/master/vite-react-ts-antd
    • Will yousrcThe source directory is embedded in my project template
    • Project root directory executionyarnInstall dependencies
    • index.hmtlImport file, I’m going to load by defaultsrc/index.tsxfile
    • performyarn devStart the project, if your code is ok at this point, alreadyrunReact17.x,ts4.x by default in my project, if you need to downgrade, please install the specified dependency)

Scaffolding instructions:

  • throughhuskyUse it every git commitprettierUnify beautification code, pass againeslintCode inspection, final usecommitlintWhether the submitted information meets the requirements to ensure code quality

These dozens of rules, I picked out one by one, because I don’t like to use things that are not clear about other people’s details, this set of rules I also hope that we use, each one has notes

Rules: {semi: ['error', 'always'], // This rule enforces the consistent semicolon 'no-unused-vars': 'off', and disallows the unused variable 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', // Production environment disables debugger 'no-console': process.env.node_env === 'production'? 'error' : 'off', // Production environment disables console 'default-case': [' WARN ', {commentPattern: '^no default$'}], // Require Switch statement default 'dot-location': ['warn', 'property'], // force a newline before or after the dot: ['error', 'allow-null'], // require === and! == 'new-parens': 'warn', // Requires a call to the no-argument constructor with parentheses 'no-caller': 'error', // disables caller or callee 'no-const-assign': 'error', // const 'no-dupe-args': 'error', // disallow duplicate arguments 'no-dupe-class-members' in function definitions: 'error', // disallow duplicate names in class members 'no-dupe-keys': 'warn', // disallow duplicate keys' no-extend-native' in object literals: 'WARN ', // disallow extension of native object 'no-extra-bind':' WARN ', // disallow unnecessary function binding 'no-fallthrough': 'error', // disallow case statement missing 'no-fun-assign ': 'WARN ', // Disallow reassigning 'no-implied-eval': 'error' to function declarations, // disallow implicit eval() 'no-label-var': 'error', // disallow the tag 'no-loop-func': 'error', // disallow the function 'no-mixed-operators': ['warn', {groups: [ ['&', '|', '^', '~', '<<', '>>', '>>>'], ['==', '!=', '===', '!==', '>', '>=', '<', '<='], ['&&', '||'], ['in', 'instanceof'],], allowSamePrecedence: false,},], // Disallow mixing of different operators 'no-multi-str': 'WARN ', // disallows multi-line strings (use \n if multiple lines are needed) 'no-native-reassign':' WARN ', // disallows reassigning the local object 'no-obj-calls': 'WARN ', // disallows calling global objects as functions 'no-redeclare': 'error', // disallows redeclaring variable 'no-script-url': 'WARN ', // Disable Script URL 'no-shadow-restricted-names': 'warn', // the keyword can't be obscured by' no-restricted-names ': 'WARN ', // disallow sparse array 'no-this-before-super':' WARN ', // disallow this or super' no-undef' in constructors before calling super() : 'error', // disallow the undeclared variable 'no-unexpected-multiline': 'WARN ', // disallow confusing multi-line expressions 'no-use-before-define': ['warn', {functions: False, classes: false, variables: false,},], // disable 'no-with': 'error', // disable with statement radix: 'error', // disable generator function 'rest-spread-spacing' with no yield inside: ['warn', 'never'], // enforce limits on Spaces between extension operators and their expressions 'react/jsx-no-undef': 'error', // disallow undeclared variable 'react/no-direct-mutation-state': 'error' in JSX, // disallow direct changes to this.state 'react/jsx-uses-react': 'WARN ', // prevent React from being incorrectly marked as not using 'no-alert': 0, // disallow alert confirm prompt 'no-duplicate-case': 2, // Switch case tag cannot repeat 'no-eq-null': 2, // forbid null == or! = operator 'no-inner-declarations': [2, 'functions'], // disallows declarations (variables or functions) 'no-iterator' in block statements: 2, // Disallow the __iterator__ attribute 'no-negated-in-lhs': 2, // The left side of the in operator cannot have! 'no-octal-escape': 2, // disallow using octal escape sequence 'no-plusplus': 0, // disallow ++, -- 'no-self-compare': 2, // cannot compare itself 'no-undef-init': // disallow unnecessary calls and apply 'init-declarations': // disallow unnecessary calls and apply 'init-declarations': // Const 'use-isnan': 2, isnan () 'vars-on-top': 2, var must be at the top of scope},Copy the code
  • Support ant-Design loading on demand
import vitePluginImp from "vite-plugin-imp"; plugins:[ ..., vitePluginImp({ libList: [ { libName: "antd", style(name) { if (/CompWithoutStyleFile/i.test(name)) { return false; } return `antd/es/${name}/style/index.css`; }, }, ],}),]Copy the code
  • Perform unaware hot updates:
import reactRefresh from "@vitejs/plugin-react-refresh";
Copy the code
  • Compatible not supportedesmThe browser
import legacy from "@vitejs/plugin-legacy";

      targets: ["defaults", "not IE 11"],
Copy the code
  • Supports ts aliases in Vite
vite.config.ts resolve: { alias: { "@": path.resolve(__dirname, "./src"), "@c": path.resolve(__dirname, "./src/components"), "@s": path.resolve(__dirname, "./src/service"), "@m": Path. Resolve (__dirname, ". / SRC/model "),,}}, tsconfig. Json "baseUrl" : ". / ", "paths" : {" @ / * ": [". / SRC / *"], "@ c / *" : ["./src/components/*"], "@m/*": ["./src/model/*"], "@s/*": ["./src/service/*"], "@t/*": ["./src/types/*"] }Copy the code

Problems encountered

  • Third party library before withwebpackPlug-ins have bindings, andviteNot supported, finally replaced the technology stack
  • viteHot update problem, this problem should be a lot of people will encounter, but I stepped on the pit a day later, did not encounter again.vitetheprodPattern building is done throughtscConverted tojsRollup is used for packaging, but firstyarn buildAfter, will be intsxnearjsFiles, such as:

At this time, whether in hot update mode or prod build, js files will be packaged, which I will delete later to solve the problem.

  • Of course,viteAnother problem with hot updates is that you can fail hot updates because of a warning, and the error location is not accurate, which can be fatal when the system becomes extremely complex.
  • Native less does not support less. You need to install the following dependencies to use them directlylessI think it’s better than thatwebpack
yarn add less less-loader -D
Copy the code

Use it and feel it

  • Development mode, thanwebpackMuch better. Basically millisecond startup and hot update speed
  • Configuration is also relatively simple, without all the webpack stuff
  • Pure, clean. There is norequire.contextThis dark magic, none of it isimport, the following code isrequire. All of them areimport.

One might ask what happens if older libraries, such as DVA, are not COMPATIBLE with ESM.

module.exports = require('./lib');
module.exports.connect = require('react-redux').connect;
Copy the code
  • So there’s a question,esmCannot be introduced directly in production modedvaAt this point, you can do a simple process, which can be prioritizeddefaultProperty, if not, take the default
import dva from "dva";
let tag = dva.default || dva;
const app = test({
  history: createHistory(),
Copy the code

Write in the last

  • See more, it is better to directly hands-on practice, clone my template down to try. Don’t forget to give me astarOpen source is not easy. There are other sources in it.https://github.com/JinJieTan/Peter-/tree/master/vite-react-ts-antd