问题描述: vue3+vite项目在按需加载的插件是vite-plugin-style-import1.3.0, 在本地运行没问题, 在jsk上构建报错
Error: [vite]: Rollup failed to resolve import "/home/jenkins/agent/workspace/ECC-ecc-pay-mobile-frontend-test/ecc_frontend/pay-mobile/node_modules/vant/lib/vant/es/cell/style" from "src/main.ts".
[2022-08-08 17:40:11] This is most likely unintended because it can break your application at runtime.
[2022-08-08 17:40:11] If you do want to externalize this module explicitly add it to
[2022-08-08 17:40:11] `build.rollupOptions.external`
[2022-08-08 17:40:11] at onRollupWarning (/home/jenkins/agent/workspace/ECC-ecc-pay-mobile-frontend-test/ecc_frontend/pay-mobile/node_modules/vite/dist/node/chunks/dep-c9998dc6.js:41797:19)
原因分析:
根据报错信息,发现是vant的样式引入路径不对。
程序解析为:项目路径/node_modules/vant/lib/vant/es/组件/style
实际应该是:项目路径/node_modules/vant/lib/ vant/es/组件/style多了一个vant/lib路径。
多了一个vant/lib路径。
而在vite.config.ts中也已经配置了按需加载的代码
import styleImport from "vite-plugin-style-import";
...
plugins: [
styleImport({
libs: [
{
libraryName: "vant",
esModule: true,
resolveStyle: (name) => `vant/es/${name}/style`
},
],
}),
],
解决方案:
考虑到vite-plugin-style-import版本更新的原因, 将这个包更新到1.4.1, 并且更新代码
import styleImport, { VantResolve } from "vite-plugin-style-import";
plugins: [
styleImport({
resolves: [VantResolve()],
libs: [
{
libraryName: "vant",
esModule: true,
resolveStyle: (name) => `vant/es/${name}/style`
},
],
}),
],
修改后, 运行没问题, 打包没问题, 大功告成!