Webpack转Vite(React项目)

318 阅读2分钟
Webpack启动方式

将所有模块打成bundle后,通过devServer启动

Vite启动方式

先启动devServer,浏览器请求哪个模块,再对相应的模块进行实时编译。

现代浏览器本身支持ES Module的功能,会自动向依赖的Module发出请求。

所以Vite在启动的时候不需要打包,意味着不需要分析模块依赖、不需要编译。

因此启动速度非常快。当浏览器请求某个模块时,再根据需要对模块内容进行编译。

Webpack 转 Vite实践
  1. 安装wp2vite
sudo npm install -g wp2vite
  1. 执行wp2vite
wp2vite

image.png 3. 安装依赖

npm install
  1. 在新生成的根目录下的index.html中加入需要额外引入的依赖,如iconfont.js
  2. 修改vite.config.js中的proxy

注意原有的pathRewrite改成rewrite,并且需要是函数形式

{
  '/api': {
    target: 'http://xxxxxxx/', 
    changeOrigin: true,
    rewrite: path => path.replace(/^\/api/, '')
  }
}
  1. 在vite.config.js中配置tailwindcss
css: {
      postcss: {
        plugins: [require('tailwindcss'), require('autoprefixer')],
      },
    },
  1. 在vite.config.js中配置@emotion/react

参考dev.to/glocore/con…

安装@vitejs/plugin-react报错:unable to resolve dependency tree blog.csdn.net/weixin_4723…

import react from '@vitejs/plugin-react'
plugins: [
      react({
        jsxImportSource: "@emotion/react",
        babel: {·
          plugins: ["@emotion/babel-plugin"],
        },
      }),
    ]
  1. 处理全局变量
(1) 将项目中REACT_APP_*替换成VITE_*,并处理相关逻辑
(2) 修改package.json中的运行脚本
"scripts": {
    "vite-start": "env-cmd -f .env.development vite",
    "build:dev": "env-cmd -f .env.dev vite build --mode dev"
	}
  1. 启动

报错:# TypeError: vite.createFilter is not a function blog.csdn.net/shentian885…

npm run vite-start
耗时对比
工具线上打包时长本地启动时长本地首次加载首页时间从首页点击打开其他页面时间
Webpack356s45s0(秒开,感觉不到慢)0
Vite352s2.1s15s4s

综上,在当前项目中,虽然Vite本地构建打开首页总耗时17S 相比于Webpack本地构建所需 45s 快,但后续打开新的页面还需加载较长时间,比较消耗耐心,不如刚开始多等一会,所以放弃转Vite。

后续有时间可以调研thread-loader加速,或者esbuild加速。