我如何汇报“过程” Vite Dev服务器中的节点模块?

发布于 2025-01-28 13:32:25 字数 303 浏览 4 评论 0原文

在我的Vite项目中,我取决于一个模块,该模块在其功能之一中使用Process节点global。我不会从我的代码中调用此功能,但是当我导入模块时, vite dev 服务器仍然会给我这个错误:

Uncaught ReferenceError: process is not defined

有趣的是,当我创建生产构建时,我看不到此错误。

如何使用no-op polyfill Process,以使Vite Dev Server停止失败?

In my Vite project, I am depending on a module that makes use of the process Node global in one of its functions. I don't call this function from my code, but the Vite dev server still gives me this error when I import the module:

Uncaught ReferenceError: process is not defined

Interestingly, I don't see this error when I create a production build.

How can I polyfill process with a no-op so that the Vite dev server stops failing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

瞄了个咪的 2025-02-04 13:32:25

今天,我在使用crolup + vite的一个React项目中也遇到了同样的问题,这就是我解决的方法,使用 Fabiano Taioli的中型作品

vite需要node.js polyfills

您需要添加一些polyfill插件以允许节点Globals,例如Process。幸运的是,您可以简单地编辑(或创建)vite.config.js

示例vite.config.js

是一个示例,其中包括使用nodeglobalspolyfillplugin to polyfill process。它还包括许多其他节点全球群体,因此在闲暇时删除。

import { defineConfig } from 'vite';
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';
import ReactPlugin from 'vite-preset-react';
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'
// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill,
      // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
      // process and buffer are excluded because already managed
      // by node-globals-polyfill
      util: 'rollup-plugin-node-polyfills/polyfills/util',
      sys: 'util',
      events: 'rollup-plugin-node-polyfills/polyfills/events',
      stream: 'rollup-plugin-node-polyfills/polyfills/stream',
      path: 'rollup-plugin-node-polyfills/polyfills/path',
      querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
      punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
      url: 'rollup-plugin-node-polyfills/polyfills/url',
      string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
      http: 'rollup-plugin-node-polyfills/polyfills/http',
      https: 'rollup-plugin-node-polyfills/polyfills/http',
      os: 'rollup-plugin-node-polyfills/polyfills/os',
      assert: 'rollup-plugin-node-polyfills/polyfills/assert',
      constants: 'rollup-plugin-node-polyfills/polyfills/constants',
      _stream_duplex:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
      _stream_passthrough:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
      _stream_readable:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
      _stream_writable:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
      _stream_transform:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
      timers: 'rollup-plugin-node-polyfills/polyfills/timers',
      console: 'rollup-plugin-node-polyfills/polyfills/console',
      vm: 'rollup-plugin-node-polyfills/polyfills/vm',
      zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
      tty: 'rollup-plugin-node-polyfills/polyfills/tty',
      domain: 'rollup-plugin-node-polyfills/polyfills/domain',
    },
  },
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: 'globalThis',
      },
      // Enable esbuild polyfill plugins
      plugins: [
        NodeGlobalsPolyfillPlugin({
          process: true,
          buffer: true,
        }),
        NodeModulesPolyfillPlugin(),
      ],
    },
  },
  plugins: [
    ReactPlugin({
      injectReact: false,
    }),
    rollupNodePolyFill(),
  ],
});

将上述示例工作所需的开发依赖项

需要添加一些依赖项。尤其:

yarn add --dev vite-preset-react
yarn add --dev @esbuild-plugins/node-modules-polyfill
yarn add --dev @esbuild-plugins/node-globals-polyfill

I had the same issue today in a React project using rollup + vite and here's how I solved it, using this Medium piece by Fabiano Taioli.

Vite needs Node.js polyfills

You need to add some polyfill plugins to allow Node globals, such as process. Fortunately, you can simply edit (or create) the vite.config.js.

Example vite.config.js

Below is an example which includes using NodeGlobalsPolyfillPlugin to polyfill process. It also includes many other node globals so remove at your leisure.

import { defineConfig } from 'vite';
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';
import ReactPlugin from 'vite-preset-react';
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'
// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill,
      // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
      // process and buffer are excluded because already managed
      // by node-globals-polyfill
      util: 'rollup-plugin-node-polyfills/polyfills/util',
      sys: 'util',
      events: 'rollup-plugin-node-polyfills/polyfills/events',
      stream: 'rollup-plugin-node-polyfills/polyfills/stream',
      path: 'rollup-plugin-node-polyfills/polyfills/path',
      querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
      punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
      url: 'rollup-plugin-node-polyfills/polyfills/url',
      string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
      http: 'rollup-plugin-node-polyfills/polyfills/http',
      https: 'rollup-plugin-node-polyfills/polyfills/http',
      os: 'rollup-plugin-node-polyfills/polyfills/os',
      assert: 'rollup-plugin-node-polyfills/polyfills/assert',
      constants: 'rollup-plugin-node-polyfills/polyfills/constants',
      _stream_duplex:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
      _stream_passthrough:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
      _stream_readable:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
      _stream_writable:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
      _stream_transform:
        'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
      timers: 'rollup-plugin-node-polyfills/polyfills/timers',
      console: 'rollup-plugin-node-polyfills/polyfills/console',
      vm: 'rollup-plugin-node-polyfills/polyfills/vm',
      zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
      tty: 'rollup-plugin-node-polyfills/polyfills/tty',
      domain: 'rollup-plugin-node-polyfills/polyfills/domain',
    },
  },
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: 'globalThis',
      },
      // Enable esbuild polyfill plugins
      plugins: [
        NodeGlobalsPolyfillPlugin({
          process: true,
          buffer: true,
        }),
        NodeModulesPolyfillPlugin(),
      ],
    },
  },
  plugins: [
    ReactPlugin({
      injectReact: false,
    }),
    rollupNodePolyFill(),
  ],
});

Development dependencies required

To make the above example work as is you'll need to add some dependencies. In particular:

yarn add --dev vite-preset-react
yarn add --dev @esbuild-plugins/node-modules-polyfill
yarn add --dev @esbuild-plugins/node-globals-polyfill
兮子 2025-02-04 13:32:25

我正在使用 node-stdlib-browser ,并且非常适合它我。

以下是我的最终vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import nodeStdlibBrowser from 'node-stdlib-browser'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import inject from '@rollup/plugin-inject'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        // https://github.com/antfu/unplugin-auto-import#configuration
        AutoImport({
            dts: 'src/auto-import.d.ts',
            imports: ['vue', 'vue-router'],
            eslintrc: {
                enabled: true,
            },
        }),
        // https://github.com/antfu/unplugin-vue-components#configuration
        Components({
            dts: 'src/components.d.ts',
        }),
        // https://github.com/niksy/node-stdlib-browser#vite
        {
            ...inject({
                global: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'global'],
                process: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'process'],
                Buffer: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'Buffer'],
            }),
            enforce: 'post',
        },
    ],
    resolve: {
        alias: { '@': path.resolve(__dirname, 'src'), ...nodeStdlibBrowser },
    },
    optimizeDeps: {
        esbuildOptions: {
            target: 'esnext', // Enable Big integer literals
        },
    },
    build: {
        target: 'esnext', // Enable Big integer literals
        commonjsOptions: {
            transformMixedEsModules: true, // Enable @walletconnect/web3-provider which has some code in CommonJS
        },
    },
})

I'm using node-stdlib-browser, and it works really well for me.

And the following is my final vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import nodeStdlibBrowser from 'node-stdlib-browser'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import inject from '@rollup/plugin-inject'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        // https://github.com/antfu/unplugin-auto-import#configuration
        AutoImport({
            dts: 'src/auto-import.d.ts',
            imports: ['vue', 'vue-router'],
            eslintrc: {
                enabled: true,
            },
        }),
        // https://github.com/antfu/unplugin-vue-components#configuration
        Components({
            dts: 'src/components.d.ts',
        }),
        // https://github.com/niksy/node-stdlib-browser#vite
        {
            ...inject({
                global: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'global'],
                process: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'process'],
                Buffer: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'Buffer'],
            }),
            enforce: 'post',
        },
    ],
    resolve: {
        alias: { '@': path.resolve(__dirname, 'src'), ...nodeStdlibBrowser },
    },
    optimizeDeps: {
        esbuildOptions: {
            target: 'esnext', // Enable Big integer literals
        },
    },
    build: {
        target: 'esnext', // Enable Big integer literals
        commonjsOptions: {
            transformMixedEsModules: true, // Enable @walletconnect/web3-provider which has some code in CommonJS
        },
    },
})
风和你 2025-02-04 13:32:25

在2024年,我建议使用 vite-plugin-node-polyfills 包裹。

PROS:更容易使用,配置和理解

cons:具有很多DEV依赖性

步骤:

1。)添加“ Vite-Plugin-Node-Polyfills”为DEV依赖关系:

# npm
npm install --save-dev vite-plugin-node-polyfills

# pnpm
pnpm install --save-dev vite-plugin-node-polyfills

# yarn
yarn add --dev vite-plugin-node-polyfills

并将“ nodepolyfills”添加为来自“ vite-plugin-node-polyfills”的插件:

import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'

export default defineConfig({
  // ... your other config
  plugins: [
    // ... your other plugins
    nodePolyfills({
      // To add only specific polyfills, add them here. If no option is passed, adds all polyfills
      include: ['process'],
      globals: { global: true, process: true },
    }),
  ],
})

2。)打开您的vite config file (例如“ vite.config.js”) 这一切都需要吗?

Vite不包括节点的核心模块。使用此软件包,您可以将任何node.js内置模块,多填充特定的全球群体或覆盖特定模块的默认polyfills覆盖。 npmjs上的检查包

In 2024 I would advise usage of vite-plugin-node-polyfills package.

Pros: It's much easier to use, configure and understand

Cons: Has lot of dev dependencies

Steps:

1.) Add "vite-plugin-node-polyfills" as dev dependency:

# npm
npm install --save-dev vite-plugin-node-polyfills

# pnpm
pnpm install --save-dev vite-plugin-node-polyfills

# yarn
yarn add --dev vite-plugin-node-polyfills

2.) Open your Vite config file (e.g. "vite.config.js") and add "nodePolyfills" as a plugin from "vite-plugin-node-polyfills" with this config:

import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'

export default defineConfig({
  // ... your other config
  plugins: [
    // ... your other plugins
    nodePolyfills({
      // To add only specific polyfills, add them here. If no option is passed, adds all polyfills
      include: ['process'],
      globals: { global: true, process: true },
    }),
  ],
})

Why is this all needed?

Vite does not include Node's Core Modules. With this package you can polyfill any Node.js Built-in Module, polyfill specific globals or override the default polyfills for specific modules. Check package on npmjs

冷夜 2025-02-04 13:32:25

替代方案是添加到您的index.html

<script type="module">
  import process from 'process';
  window.process = process;
</script>

An alternative is adding to your index.html

<script type="module">
  import process from 'process';
  window.process = process;
</script>
凉宸 2025-02-04 13:32:25

请使用“ Esbuild-Plugin-Polyfill节点”插件。
https://npm.io/package/esbuild-plugin-plugin-polugin-polyfill-polyfill-node
这为我解决了问题,无需在脚本标签中手动添加和分配global = window

Please use 'esbuild-plugin-polyfill-node' plugin.
https://npm.io/package/esbuild-plugin-polyfill-node
This solved the problem for me, and NO NEEDED of manually adding and assigning global = window in script tag.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文