vitejs / vite

Next generation frontend tooling. It's fast!
http://vitejs.dev
MIT License
66.82k stars 6k forks source link

Error: Module "events" has been externalized for browser compatibility #9238

Closed sgnilreutr closed 2 years ago

sgnilreutr commented 2 years ago

Describe the bug

After upgrading to Vite 3.0.2 (since 2.X version has some production level bugs for me) - the production version started working, but the development is crashing due to the following error:

`Uncaught Error: Module "events" has been externalized for browser compatibility. Cannot access "events.EventEmitter" in client code. get events:9 js Parser.js:133 require chunk-QOVRSCHT.js:11 js index.js:1 require chunk-QOVRSCHT.js:11

HtmlParser.js:1 [events:9:12](browser-external:events) get events:9 js Parser.js:133 __require chunk-QOVRSCHT.js:11 js index.js:1 __require chunk-QOVRSCHT.js:11 HtmlParser.js:1 InnerModuleEvaluation self-hosted:2361 InnerModuleEvaluation self-hosted:2361 InnerModuleEvaluation self-hosted:2361 InnerModuleEvaluation self-hosted:2361 InnerModuleEvaluation self-hosted:2361 InnerModuleEvaluation self-hosted:2361 evaluation self-hosted:2322` After removing the mentioned dependency 'HtmlParser' -> https://www.npmjs.com/package/react-html-parser -> the installation seems to work. ### Reproduction https://stackblitz.com/edit/react-rj6cc2 ### System Info ```shell System: OS: macOS 12.4 CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz Memory: 36.39 MB / 16.00 GB Shell: 5.8.1 - /bin/zsh Binaries: Node: 16.13.1 - /usr/local/bin/node Yarn: 1.22.19 - /usr/local/bin/yarn npm: 8.1.2 - /usr/local/bin/npm Watchman: 2022.07.04.00 - /usr/local/bin/watchman Browsers: Chrome: 103.0.5060.114 Firefox Developer Edition: 103.0 Safari: 15.5 npmPackages: @vitejs/plugin-react: 2.0.0 => 2.0.0 vite: 3.0.0 => 3.0.0 ``` ### Used Package Manager yarn ### Logs _No response_ ### Validations - [X] Follow our [Code of Conduct](https://github.com/vitejs/vite/blob/main/CODE_OF_CONDUCT.md) - [X] Read the [Contributing Guidelines](https://github.com/vitejs/vite/blob/main/CONTRIBUTING.md). - [X] Read the [docs](https://vitejs.dev/guide). - [X] Check that there isn't [already an issue](https://github.com/vitejs/vite/issues) that reports the same bug to avoid creating a duplicate. - [X] Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to [vuejs/core](https://github.com/vuejs/core) instead. - [X] Check that this is a concrete bug. For Q&A open a [GitHub Discussion](https://github.com/vitejs/vite/discussions) or join our [Discord Chat Server](https://chat.vitejs.dev/). - [X] The provided reproduction is a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of the bug.
sapphi-red commented 2 years ago

Would you provide a minimal repro, not the entire project?

github-actions[bot] commented 2 years ago

Hello @sgnilreutr. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with need reproduction will be closed if they have no activity within 3 days.

sgnilreutr commented 2 years ago

Would you provide a minimal repro, not the entire project?

@sapphi-red initial post has been updated.

sapphi-red commented 2 years ago

react-html-parser uses htmlparser2@3.10.1 and that uses events node-builtin module. https://github.com/fb55/htmlparser2/blob/v3.10.1/lib/Parser.js#L133 events cannot be used from browser and you need to install a polyfill by yourself. https://stackblitz.com/edit/vitejs-vite-4ymyej?file=package.json&terminal=dev

Previously Vite 2 was wrongly handling this. Closing as it is working as intended.

sebsobseb commented 2 years ago

@sapphi-red does this also apply for the error I'm having about util.inspect?

I'm getting the same issue using Intertia + Laravel vite plugin:

Uncaught Error: Module "./util.inspect" has been externalized for browser compatibility. Cannot access "./util.inspect.custom" in client code.
    at Object.get (util.inspect:9:13)
    at .yarn/cache/object-inspect-npm-1.12.2-f125a822c0-a534fc1b85.zip/node_modules/object-inspect/index.js (index.js:69:33)
    at __require (chunk-OL3AADLO.js?v=ac4fe6e7:9:50)
    at .yarn/cache/side-channel-npm-1.0.4-e1f38b9e06-351e41b947.zip/node_modules/side-channel/index.js (index.js:5:15)
    at __require (chunk-OL3AADLO.js?v=ac4fe6e7:9:50)
    at .yarn/cache/qs-npm-6.11.0-caf1bc9dea-6e1f29dd53.zip/node_modules/qs/lib/stringify.js (stringify.js:3:22)
    at __require (chunk-OL3AADLO.js?v=ac4fe6e7:9:50)
    at .yarn/cache/qs-npm-6.11.0-caf1bc9dea-6e1f29dd53.zip/node_modules/qs/lib/index.js (index.js:3:17)
    at __require (chunk-OL3AADLO.js?v=ac4fe6e7:9:50)
    at .yarn/cache/@inertiajs-inertia-npm-0.11.0-d50fb317f9-69653f3cb4.zip/node_modules/@inertiajs/inertia/dist/index.js (index.js:1:99)

More details can be found here: https://github.com/laravel/vite-plugin/issues/102

sapphi-red commented 2 years ago

@sebsobseb That one is a bug. It's a reported at #9092, https://github.com/vitejs/vite/issues/7576. (The reason is same: https://github.com/vitejs/vite/pull/7599)

sebsobseb commented 2 years ago

@sapphi-red ok, thanks for confirming. I just had a look at that PR https://github.com/vitejs/vite/pull/7599 - Any idea when approx it will be merged/tagged?

sapphi-red commented 2 years ago

@sebsobseb #7599 won't be merged because it only explains the reason of the bug. #9170 might fix this but I've not checked yet. If you create a reproduction without laravel/vite-plugin in stackblitz, I'll try to find a workaround.

sebsobseb commented 2 years ago

@sapphi-red Ok, fair enough, appreciate the help. The strange thing is that i cannot reproduce it without the laravel/vite-plugin: https://stackblitz.com/edit/vite-whdqvh?file=main.js

Simply importing import objectInspect from 'object-inspect'; should trigger the error.

With the plugin (on my machine) this throws the following error in the console:

[util.inspect:9] Uncaught Error: Module "./util.inspect" has been externalized for browser compatibility. Cannot access "./util.inspect.custom" in client code.
    at Object.get (util.inspect:9:13)
    at .yarn/cache/object-inspect-npm-1.12.2-f125a822c0-a534fc1b85.zip/node_modules/object-inspect/index.js (index.js:69:33)
    at __require (chunk-OL3AADLO.js?v=736966f0:9:50)
    at dep:object-inspect:1:16

Do you reckon it could be because of the plugin or because of my machine? This is what the config of the plugin looks like: https://github.com/laravel/vite-plugin/blob/main/src/index.ts

The other difference is that i'm using Yarn 3.2.1, in stackblitz it's v1.22.

sebsobseb commented 2 years ago

✅ The issue disappeared when I switched from Yarn to NPM 🤷‍♂️

sapphi-red commented 2 years ago

@sebsobseb Umm. Does it reproduce if you import inertia.js instead of directly importing object-inspect?

otaviosoares commented 2 years ago

The issue disappeared when I switched from Yarn to NPM

Yeah, the issue seems to be related pnp mode only. I switched to yarn's node-modules linker and the problem is gone.

Ken-vdE commented 2 years ago

@sapphi-red I'm having the same issue when trying to import { Device } from '@twilio/voice-sdk'; (https://www.npmjs.com/package/@twilio/voice-sdk). image Because eventtarget.js tries running const EventEmitter = require('events').EventEmitter;.

I've tried adding the 'events' package (https://www.npmjs.com/package/events), but then I run into a similar issue: image

I've also tried installing 'rollup-plugin-node-polyfills' (https://www.npmjs.com/package/rollup-plugin-node-polyfills) and setting it in vite.config.js

    build: {
        rollupOptions: {
            plugins: [
                rollupNodePolyFill(),
            ],
        },
    },
    resolve: {
        alias: [
            { find: 'events', replacement: 'rollup-plugin-node-polyfills/polyfills/events' },
            { find: 'child_process', replacement: 'rollup-plugin-node-polyfills' },
            { find: 'path', replacement: 'rollup-plugin-node-polyfills/polyfills/path' },
        ],
    },

but then I run into image

So then I add this to vite.config.js:

    define: {
        process: {
            env: {},
        },
    },

But then this is thrown: image

Then I found this post https://stackoverflow.com/a/70666018/3017716 and added those things to the vite.config.js. It seems to be working now...

justin0mcateer commented 2 years ago

The StackOverflow answer mentioned above also worked for me...

blobinabottle commented 2 years ago

Fighting with the polypill nightmare. Anyone is able to fix the issue with Sveltekit/vite?

This is the config I'm using (process and buffer are not warning anymore so I guess it's "working" but I'm stuck on events)

import nodePolyfills from "rollup-plugin-polyfill-node";

import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";

export default defineConfig({
  plugins: [nodePolyfills({ include: null }), svelte()],
});
justin0mcateer commented 2 years ago

See that link on Stack Overflow, you need to use a 'resolve' block and specifically map the 'events' import to a file on that polyfill. Also, there is a newer version of the polyfill: https://github.com/FredKSchott/rollup-plugin-polyfill-node

Look in the 'polyfills' directory and you will see all of the node modules that you can alias.

Get Outlook for Androidhttps://aka.ms/AAb9ysg


From: Lionel @.> Sent: Saturday, August 6, 2022 12:06:31 PM To: vitejs/vite @.> Cc: justin0mcateer @.>; Comment @.> Subject: Re: [vitejs/vite] Error: Module "events" has been externalized for browser compatibility (Issue #9238)

Fighting with the polypill nightmare. Anyone is able to fix the issue with Sveltekit/vite?

This is the config I'm using (process and buffer are not warning anymore so I guess it's "working" but I'm stuck on events)

import nodePolyfills from "rollup-plugin-polyfill-node";

import { defineConfig } from "vite"; import { svelte } from @.***/vite-plugin-svelte";

export default defineConfig({ plugins: [nodePolyfills({ include: null }), svelte()], });

— Reply to this email directly, view it on GitHubhttps://github.com/vitejs/vite/issues/9238#issuecomment-1207248242, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AAT4Q7I67SHOSWK57EZTYY3VX2LRPANCNFSM54CD2BLA. You are receiving this because you commented.Message ID: @.***>

blobinabottle commented 2 years ago

Ah man, thanks a lot! I tried that initially and got some weird errors with string_encoder but it turns out it's not necessary.

Do you know if it has an impact to add all the polyfills (so we could always use the same config file in different projects) or is it best to only add the ones needed?

justin0mcateer commented 2 years ago

My thought was to minimize the aliases. Overtime, I plan to try to eliminate these with different deps or upstream patches.

I did run into a problem with one polyfill depending on a different one (process) and it wasn't referenced, so it wasn't resolving. I had to add an import to get it to work correctly.

Get Outlook for Androidhttps://aka.ms/AAb9ysg


From: Lionel @.> Sent: Sunday, August 7, 2022 3:12:45 AM To: vitejs/vite @.> Cc: justin0mcateer @.>; Comment @.> Subject: Re: [vitejs/vite] Error: Module "events" has been externalized for browser compatibility (Issue #9238)

Ah man, thanks a lot! I tried that initially and got some weird errors with string_encoder but it turns out it's not necessary.

Do you know if it has an impact to add all the polyfills (so we could always use the same config file in different projects) or is it best to only add the ones needed?

— Reply to this email directly, view it on GitHubhttps://github.com/vitejs/vite/issues/9238#issuecomment-1207355113, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AAT4Q7MS5GPNNBIUK5XMYVTVX5VX3ANCNFSM54CD2BLA. You are receiving this because you commented.Message ID: @.***>