项目场景:
用vite4+react+ts+jest+lerna+storybook搭建的组件库
问题描述
用es2020新语法编写的组件库,通过npm软连接测试组件时,发现用vite打包之后的组件项目上引用报错
Module parse failed: Unexpected token (50587:43)
File was processed with these loaders:
* ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
You may need an additional loader to handle the result of these loaders.
| }
| let Ii = Rt ? Rt.getColor(ui) : void 0;
> Ft && (Ii = `rgba(0, 84, 255, ${(ui ?? 1) * 1 / 100})`), At.push({
| geometry: ye == null ? void 0 : ye.geometry,
| properties: {
原因分析:
发现es2020语法“??”不支持,查阅vite官方文档,里面说库模式打包,默认会打包成es2020版本,而使用组件的项目,最多只能支持es2015,所以,这里报错信息提示你添加新的loader来处理,但是治标不治本,因为其它项目用到你的组件库同样也会报错。
解决方案:
在组件库的vite打包配置上,配置"target"项的版本为“es2015”即可
......
build: {
......
target: 'es2015',
}