如何在ViteJS中无需主文件引用,通过manualChunks打包EditorJS?
如何在Vite中单独打包未被主代码引用的EditorJS
针对你在Vite+PHP开发中想要单独打包EditorJS(即便主代码没直接引用)的需求,除了多入口方案外,还有几个更简洁的实现方式:
方案1:用import.meta.glob配合manualChunks强制标记依赖
不用写伪console.log,只需要在主入口文件(比如main.js)里加一行静态导入声明,告诉Rollup这个依赖需要被打包:
// 仅用于告知Rollup要处理EditorJS,运行时不会实际加载 import.meta.glob('editorjs', { eager: false, import: 'default' });
然后在Vite配置里的rollupOptions中配置manualChunks:
export default defineConfig({ build: { rollupOptions: { output: { manualChunks: { editorjs: ['editorjs'] } } } } });
这样Rollup会识别到EditorJS是需要打包的依赖,生成的editorjs chunk就不会是空文件,也不需要在业务代码里实际使用它。
方案2:用Rollup插件强制注入依赖
安装@rollup/plugin-inject插件后,通过配置让Rollup强制将EditorJS纳入打包流程,无需修改业务代码:
import inject from '@rollup/plugin-inject'; export default defineConfig({ build: { rollupPlugins: { before: [ inject({ EditorJS: 'editorjs' }) ] }, rollupOptions: { output: { manualChunks: { editorjs: ['editorjs'] } } } } });
这个插件会让Rollup认为项目中引用了EditorJS,从而正常生成对应的独立chunk。
方案3:优化版多入口配置(你已尝试的方案)
如果用多入口,不用直接引用node_modules里的文件,可以新建一个极简入口文件(比如src/editorjs-entry.js),里面只写一行导入:
import EditorJS from 'editorjs'; // 不需要额外代码,仅用于让Rollup识别依赖
然后在Vite配置里指定多入口:
export default defineConfig({ build: { rollupOptions: { input: { main: './src/main.js', editorjs: './src/editorjs-entry.js' } } } });
这种方式更清晰,也方便后续对EditorJS做自定义处理(比如暴露全局变量)。
方案选择建议
- 单纯需要单独打包EditorJS,方案1最简洁,无需额外文件或插件;
- 批量处理多个未被引用的依赖,方案2更高效;
- 需要对EditorJS的打包输出做自定义修改,方案3更灵活。
内容的提问来源于stack exchange,提问作者Potivier
相关产品推荐
相关产品推荐

