Write at the beginning
- Before, many of my friends have already upgraded to
vite
, but most of them are vue project, so today we have beforewebpack
ofreact
upgrade the project tovite
! - For this reason, in order to let everyone step on the pit, I first
china-dev.cn
the website projectvite
- For online drawing functions, may have little impact, but writing with online
javascript
this feature big impact, because before using the library, will followwebpack
binding, does not currently supportvite
, so I replaced the technology stack, but the results but better This shows thatwebpack
is a false proposition. The method is always more difficult than the difficulty, and the construction tool is just a choice.
PS: This website is always free, and there are a lot of front-end free learning materials inside. For this reason, I took this project away from the business part and made a simple project template
Officially begin
If you haven't read what I wrote before: the core difference between webpack and vite, I suggest you read it first, then read this article
The first thing to be solved when webpack migrates to vite:
- It is not a good thing to decouple the plug-ins & technology stacks strongly associated with
webpack
. At any time, it is not a good thing to rely on a third-party tool & environment. At this point, architects who have done heavy system deployment, I believe they have this feeling - Except
import
project, all replaced with the introduction ofimport
It can be said thatesm
is a trend, because it is a specification.vue3
no longer supportsie11
, it is only time to replace the old domestic system, this is a big trend,some official websites in Shenzhen have begun to recommend you to use a new browser~
- Standardize your code so that there are
typescript
type errors such asvite
and other warnings, etc. The hot update of 06082afc23402d is very fragile. It is possible that a small warning or irregular writing will cause the hot update to fail, and the error location is not accurate, or It does not report an error directly, but fails (the pits will be described below)
- It is not a good thing to decouple the plug-ins & technology stacks strongly associated with
Next, clone my scaffold to the local
- Address
https://github.com/JinJieTan/Peter-/tree/master/vite-react-ts-antd
- Put your
src
source directory into my project template - The project root directory executes
yarn
installation dependencies index.hmtl
entry file, my default here is to load thesrc/index.tsx
file- Execute
yarn dev
and start the project. If your code isrun
up (the default version in my project is react17.x, ts4.x, if you need to downgrade, please install the specified dependencies)
- Address
Scaffolding description:
- By
husky
using git commit every timeprettier
unified beautification code, and then byeslint
code detection, end-usecommitlint
submit information to meet the requirements, in order to ensure code quality
These dozens of rules are carefully selected one by one, because I don’t like to use things that don’t know the details of others. I also hope that you will use this set of rules. Each one has a comment.
rules: {
semi: ['error', 'always'], // 该规则强制使用一致的分号
'no-unused-vars': 'off', // 禁止未使用过的变量
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', //生产环境禁用 debugger
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', //生产环境禁用 console
'default-case': ['warn', { commentPattern: '^no default$' }], //要求 Switch 语句中有 Default
'dot-location': ['warn', 'property'], // 强制在点号之前或之后换行
eqeqeq: ['error', 'allow-null'], //要求使用 === 和 !==
'new-parens': 'warn', //要求调用无参构造函数时带括号
'no-caller': 'error', // 禁用 caller 或 callee
'no-const-assign': 'error', //不允许改变用 const 声明的变量
'no-dupe-args': 'error', //禁止在 function 定义中出现重复的参数
'no-dupe-class-members': 'error', //不允许类成员中有重复的名称
'no-dupe-keys': 'warn', //禁止在对象字面量中出现重复的键
'no-extend-native': 'warn', //禁止扩展原生对象
'no-extra-bind': 'warn', //禁止不必要的函数绑定
'no-fallthrough': 'error', //禁止 case 语句落空
'no-func-assign': 'warn', //禁止对 function 声明重新赋值
'no-implied-eval': 'error', //禁用隐式的 eval()
'no-label-var': 'error', //禁用与变量同名的标签
'no-loop-func': 'error', //禁止循环中存在函数
'no-mixed-operators': [
'warn',
{
groups: [
['&', '|', '^', '~', '<<', '>>', '>>>'],
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
['&&', '||'],
['in', 'instanceof'],
],
allowSamePrecedence: false,
},
], //禁止混合使用不同的操作符
'no-multi-str': 'warn', //禁止多行字符串 (需要多行时用\n)
'no-native-reassign': 'warn', //禁止重新分配本地对象
'no-obj-calls': 'warn', //禁止将全局对象当作函数进行调用
'no-redeclare': 'error', //禁止重新声明变量
'no-script-url': 'warn', //禁用 Script URL
'no-shadow-restricted-names': 'warn', //关键字不能被遮蔽
'no-sparse-arrays': 'warn', //禁用稀疏数组
'no-this-before-super': 'warn', //在构造函数中禁止在调用 super()之前使用 this 或 super
'no-undef': 'error', //禁用未声明的变量
'no-unexpected-multiline': 'warn', //禁止使用令人困惑的多行表达式
'no-use-before-define': [
'warn',
{
functions: false,
classes: false,
variables: false,
},
], //禁止定义前使用
'no-with': 'error', //禁用 with 语句
radix: 'error', //禁用函数内没有 yield 的 generator 函数
'rest-spread-spacing': ['warn', 'never'], //强制限制扩展运算符及其表达式之间的空格
'react/jsx-no-undef': 'error', //在 JSX 中禁止未声明的变量
'react/no-direct-mutation-state': 'error', //禁止 this.state 的直接变化
'react/jsx-uses-react': 'warn', //防止 React 被错误地标记为未使用
'no-alert': 0, //禁止使用alert confirm prompt
'no-duplicate-case': 2, //switch中的case标签不能重复
'no-eq-null': 2, //禁止对null使用==或!=运算符
'no-inner-declarations': [2, 'functions'], //禁止在块语句中使用声明(变量或函数)
'no-iterator': 2, //禁止使用__iterator__ 属性
'no-negated-in-lhs': 2, //in 操作符的左边不能有!
'no-octal-escape': 2, //禁止使用八进制转义序列
'no-plusplus': 0, //禁止使用++,--
'no-self-compare': 2, //不能比较自身
'no-undef-init': 2, //变量初始化时不能直接给它赋值为undefined
'no-useless-call': 2, //禁止不必要的call和apply
'init-declarations': 0, //声明时必须赋初值
'prefer-const': 0, //首选const
'use-isnan': 2, //禁止比较时使用NaN,只能用isNaN()
'vars-on-top': 2, //var必须放在作用域顶部
},
- 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`;
},
},
],
}),
]
- Perform a non-perceived hot update:
import reactRefresh from "@vitejs/plugin-react-refresh";
plugins:[
...,
reactRefresh(),
]
- Compatible with browsers that do not support
esm
import legacy from "@vitejs/plugin-legacy";
plugins:[
...,
legacy({
targets: ["defaults", "not IE 11"],
}),
]
- Support ts alias configuration 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/*"]
}
Problems encountered
- The third-party library was previously
webpack
plug-in, butvite
did not support it. Finally, the technology stack was replaced. vite
hot update problem, this problem should be encountered by many people, but after I stepped on the pit for a day, I did not encounter it again.vite
ofprod
model constructed bytsc
converted intojs
After then packaged by ROLLUP, but firstyarn build
later, will be intsx
generated nearjs
file, for example:
At this time, whether it is hot update mode or prod build, the js file will be packaged, and this problem will be solved after I delete it later.
- Of course,
vite
hot update, that is, you may fail the hot update because of a warning, and the error location is not accurate. When the system becomes extremely complex, this problem is fatal. - The native does not support less, you need to install the following dependencies, you can directly introduce and use
less
, which I think is better thanwebpack
yarn add less less-loader -D
Use it to feel
- The development model is
webpack
better than 06082afc23453f. Basically millisecond-level startup and hot update speed - The configuration is also relatively simple, without a lot of things like webpack
- Pure and clean. No
require.context
this black magic, the above is notimport
, following which the code isrequire
. All areimport
.
Some people may ask, what if the old library is not compatible withesm
, such asdva
.
module.exports = require('./lib');
module.exports.connect = require('react-redux').connect;
- There is a problem.
esm
cannot directly introduce 06082afc2345c0 in the production mode.dva
this time, a simple process can be done. You can take thedefault
attribute first. If you can’t get it, use the default
import dva from "dva";
let tag = dva.default || dva;
const app = test({
history: createHistory(),
});
Write at the end
- No matter how much you see, it's better to practice directly, clone this template and try it out. Don’t forget to give a
star
, open source is not easy, there are other source code inside,https://github.com/JinJieTan/Peter-/tree/master/vite-react-ts-antd
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。