截至2024年9月,vue-cli已经不怎么更新了,vue-cli基于webpack创建,迁移到vite的成本并不算低,还好有rsbuild,兼容webpack,让迁移成本大大降低。
rsbuild 是rspack的上层封装,配置更简单些。
依赖安装
json
代码解读
复制代码
// package.json { "scripts": { "dev": "rsbuild dev --env-mode serve", "build": "rsbuild build --env-mode build", //... }, "dependencies": { "vue": "^3.5.8", //... }, "devDependencies": { "@rsbuild/core": "^1.0.1", "@rsbuild/plugin-babel": "^1.0.1", "@rsbuild/plugin-sass": "^1.0.1", "@rsbuild/plugin-vue": "^1.0.1", "@rsbuild/plugin-vue-jsx": "^1.0.1", //... } }
在vite里面用--mode
可以指定读取哪一个env文件,在rsbuild下用--env-mode
。
rsbuild配置
项目根目录下rsbuild.config.ts
ts
代码解读
复制代码
import { defineConfig, loadEnv } from "@rsbuild/core"; import { pluginBabel } from "@rsbuild/plugin-babel"; import { pluginVue } from "@rsbuild/plugin-vue"; import { pluginVueJsx } from "@rsbuild/plugin-vue-jsx"; import { pluginSass } from "@rsbuild/plugin-sass"; const { parsed, publicVars } = loadEnv({ prefixes: ["VUE_APP_"] }); export default defineConfig({ source: { entry: { index: "./src/main.ts", }, define: { ...publicVars, }, }, html: { template: "./public/index.html", templateParameters: { VUE_APP_TITLE: parsed.VUE_APP_TITLE, }, }, plugins: [ pluginBabel({ include: /\.(?:jsx|tsx)$/, }), pluginVue(), pluginVueJsx(), pluginSass(), ], server: { port: 4433, proxy: { "/api": { target: "http://proxy.com/api/", changeOrigin: true, pathRewrite: { "^/api": "", }, }, }, }, });
loadEnv
可以读取.env
文件的配置,通过publicVars加到client
端- index.html 文件的变量可以通过配置
templateParameters
修改
index.html配置
html
代码解读
复制代码
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0" /> <link rel="icon" href="<%= assetPrefix %>/favicon.ico" /> <title><%= VUE_APP_TITLE %></title> <body> <noscript> <strong >We're sorry but doesn't work properly without JavaScript enabled. Please enable it to continue.</strong > </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
assetPrefix
相当于vite下的base
,是静态文件前缀,可以通过output.assetPrefix
修改VUE_APP_TITLE
在html.templateParameters
修改
tsconfig.json配置
json
代码解读
复制代码
{ "compilerOptions": { "jsx": "preserve", "jsxImportSource": "vue", "types": [ "@rsbuild/core/types", //... ], "paths": { "@/*": ["src/*"] }, //... }, //... }
- jsx 配置
"jsx": "preserve"
,"jsxImportSource": "vue"
compilerOptions.types
添加@rsbuild/core/types
注意事项
process
和import.meta
不能在client
端,也就是vue文件等直接解构使用,需要写全
ts
代码解读
复制代码
const NODE_ENV = process.env.NODE_ENV; const MODE = import.meta.env.NODE
现在你的项目就可以享受火箭般的速度啦。
原文链接:https://juejin.cn/post/7418771710453825551