【问题标题】:Inject Imports with Vite使用 Vite 注入导入
【发布时间】:2022-08-15 17:03:43
【问题描述】:

我正在使用 Vite 作为我的构建工具来构建一个苗条的前端应用程序。

我使用的一些库是需要 Buffer 模块的 Node.js 模块。为了提供 Buffer 功能,我使用了出色的 buffer 模块。我的应用程序需要缓冲功能才能工作,所以我不能只使用简单的 polyfill。我的 Vite 配置如下所示:

export default defineConfig(({ command, mode }) => {
  build: {
    target: \"esnext\",
    rollupOptions: {
      plugins: [inject({ Buffer: [\'buffer\', \'Buffer\'] })]
    }
  },
  optimizeDeps: {
    esbuildOptions: {
      define: { global: \'globalThis\' },
      plugins: [NodeGlobalsPolyfillPlugin({ process: true })]
    }
  },
  plugins: [svelte({
    experimental: { prebundleSvelteLibraries: true },
    preprocess: [sveltePreprocess({ typescript: true }), optimizeImports()]
  })]
});

问题是,虽然我的生产构建工作(缓冲区功能由rollupOptions 中的inject 插件注入),但开发构建不使用汇总,所以它失败了。我怎样才能让生产和开发版本都在需要的地方注入 Buffer 库?

  • \"我不能只用一个简单的 polyfill\"为什么?

标签: javascript svelte vite rollupjs esbuild


【解决方案1】:

我不明白为什么 polyfill 不能解决你的问题。

试着把这段代码放在你的入口 JS 文件的开头(可能是src/index.js),只是为了确保它执行Buffer global 曾经被使用过。

import { Buffer } from 'buffer';
globalThis.Buffer = Buffer; // <-- polyfill

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 2022-10-22
    • 2023-02-06
    • 2022-11-14
    • 2022-10-14
    • 2022-07-17
    • 2022-08-16
    • 2022-12-12
    相关资源
    最近更新 更多