前言:vite项目中,依赖包的加载都是基于esm模块加载的,有些依赖打包后不是esm而是CommonJS类型的,则需要由CommonJS转为esm类型。vite预构建可以默认将node_modules下的依赖包进行转换为esm类型并存放在node_modules文件夹下的.vite文件夹下,也可以自行添加路径来预构建(详见文档:https://cn.vitejs.dev/guide/dep-pre-bundling.html#customizing-the-behavior)。
对于一些老旧sdk,在vite项目中,利用pnpm link调试,就需要转包操作了。在此记录一下手动将CommonJS模块转为ESM模块的小demo。
{
"name": "cjs_to_esm",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"build": "rollup -c"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@rollup/plugin-commonjs": "^23.0.2",
"rollup": "^3.2.5"
}
}{
"name": "cjs_to_esm",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"build": "rollup -c"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@rollup/plugin-commonjs": "^23.0.2",
"rollup": "^3.2.5"
}
}
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/test_cjs.js',
output: {
file: 'output/test_esm.js',
format: 'es'
},
plugins: [commonjs()]
};import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/test_cjs.js',
output: {
file: 'output/test_esm.js',
format: 'es'
},
plugins: [commonjs()]
};
评论区