我正在使用 Vite 作为构建工具构建 chrome 扩展。主要问题是在缩小和修改过程中创建了很多全局变量。将我的脚本注入页面后,它们与窗口对象上已定义的变量发生冲突。
我想完美的解决方案是将我的整个脚本封装在 IIFE 中。我尝试使用esbuild.format = 'iife'. 生成的构建实际上包含在 IIFE 中,但是所有导入都不是内联的。相反,生成的脚本大约有 15 行长,包含一堆require语句,这显然在浏览器中不起作用。
这是我的配置文件:
export default defineConfig({
plugins: [
vue(),
],
esbuild: {
format: 'iife',
},
build: {
emptyOutDir: false,
rollupOptions: {
input: resolve(__dirname, './src/web/index.ts'),
output: {
dir: resolve(__dirname, './dist'),
entryFileNames: 'web.js',
assetFileNames: 'style.css',
},
},
},
resolve: {
alias: {
'@': resolve(__dirname, './src'),
},
},
});
Run Code Online (Sandbox Code Playgroud)
我目前正在使用这个 hack,也就是说将我的构建包装在 IIFE 中(为此我删除了该esbuild.format选项)。
嘿,我正在做同样的事情!我还注意到未缩小的变量和函数可能会与网页中的随机代码发生冲突。
根据我对此主题的研究,您不应该esbuild使用 Vite 更改构建选项,因为这会阻止 Rollup 转换输出。相反,您应该format: 'iife'在rollupOptions您的vite.config. 但是,就我而言(我相信也是您的情况),我必须输出多个包,因为扩展代码无法在彼此之间共享模块。当您将格式设置为“iife”时,由于以下原因,它将崩溃:
Invalid value for option "output.inlineDynamicImports" - multiple inputs are not supported when "output.inlineDynamicImports" is true.
Run Code Online (Sandbox Code Playgroud)
在我的情况下,唯一的解决方案似乎是为vite.configs每个包使用多个(我已经有两个),并使用单个input入口点和格式为“iife”。或者,就像您所做的那样,只需使用一些 hacky 脚本自己编写自调用函数即可。目前看来还没有完美的解决方案。
编辑:好的,开始工作了。这是我的vite.config.ts(项目):
Invalid value for option "output.inlineDynamicImports" - multiple inputs are not supported when "output.inlineDynamicImports" is true.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5773 次 |
| 最近记录: |