Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vite does not seem to support es module that depends on nodejs builtins #728

Closed
wighawag opened this issue Aug 20, 2020 · 31 comments · Fixed by #746
Closed

vite does not seem to support es module that depends on nodejs builtins #728

wighawag opened this issue Aug 20, 2020 · 31 comments · Fixed by #746
Labels
bug: upstream Bug in a dependency of Vite

Comments

@wighawag
Copy link

Describe the bug

By default vite does not include any support for es module that import nodejs builtins module (like crypto, etc...)

I tried to add the rollup-plugin-node-builtins plugin with option {crypto: true}

but I had to set a name to it as the following

import builtins from 'rollup-plugin-node-builtins';

const builtinsPlugin = builtins({crypto: true});
builtinsPlugin.name = 'builtins';

module.exports = {
    rollupInputOptions: {
        plugins: [
            builtinsPlugin
        ]
    }
  }

because otherwise I get the following error :

TypeError: Cannot read property 'includes' of undefined
    at C:\dev\projects\wighawag\svite-test\svite-typescript-minimal\node_modules\vite\dist\node\build\index.js:202:60
    at Array.findIndex (<anonymous>)
    at Object.build (C:\dev\projects\wighawag\svite-test\svite-typescript-minimal\node_modules\vite\dist\node\build\index.js:202:36)
    at async runBuild (C:\dev\projects\wighawag\svite-test\svite-typescript-minimal\node_modules\svite\bin\svite.js:176:7)
    at async Command.<anonymous> (C:\dev\projects\wighawag\svite-test\svite-typescript-minimal\node_modules\svite\bin\svite.js:401:7)
    at async Promise.all (index 0)
    at async main (C:\dev\projects\wighawag\svite-test\svite-typescript-minimal\node_modules\svite\bin\svite.js:441:3)

Also when running npm run dev it fails with various error indicating the builtins are not properly injected

Reproduction

Here is repo that uses svite (https://github.com/dominikg/svite/) where you can reproduce the issue in the branch rollup-plugin-node-builtins : https://github.com/wighawag/svite-typescript-minimal/tree/rollup-plugin-node-builtins

npm i
npm run build

to test runtime error :

npm run dev

System Info

  • required vite version: 1.0.0-rc.4
  • required Operating System: Windows 10 (64bit)
  • required Node version: 12.18.3
  • npm/yarn version : npm 6.14.6
@wighawag
Copy link
Author

I created a vite only repo with both rollup-plugin-node-builtins and rollup-plugin-node-globals plugins setup
the fix for plugin name is included but got runtime error : https://github.com/wighawag/vite-test
see : https://github.com/wighawag/vite-test/blob/99603efde5819f4f67f04a00037d2f0ecb2dc41a/vite.config.js#L5

@intrnl
Copy link
Contributor

intrnl commented Aug 25, 2020

Node builtins doesn't work in browser and Vite doesn't provide any shimming/polyfills for it.

Rollup plugins are only run during builds, you need to provide a middleware to the dev server

edit: i might check what's up with the build failing

@wighawag
Copy link
Author

Ok, thanks for the info.

The build is failing because the code expect plugin to have a name field.
and rollup-plugin-node-builtins does not have it

@underfin
Copy link
Member

@wighawag. The name with plugin is necessary, you can ask the maintainer of rollup-plugin-node-builtins add this or add name with yourself. For build error, I pushed the pr to fix it and please wait rollup/plugins#554 (comment) be resolved.

@antfu antfu added bug: upstream Bug in a dependency of Vite and removed bug labels Aug 26, 2020
@intrnl
Copy link
Contributor

intrnl commented Aug 26, 2020

{ ...builtins({ crypto: true }), name: 'rollup-plugin-node-builtins' } should do as a workaround

@underfin
Copy link
Member

underfin commented Sep 7, 2020

@wighawag. This is can be closed. You can track here rollup/rollup#3765 for object prototype is lost .

@sujit-baniya
Copy link

@underfin I did this in vite.config.js but still getting error require is not a function

import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';

const builtinsPlugin = builtins({crypto: true});
builtinsPlugin.name = 'builtins'; // required, see https://github.com/vitejs/vite/issues/728

const globalsPlugin = globals();
globalsPlugin.name = 'globals'; // required, see https://github.com/vitejs/vite/issues/728

module.exports = {
    assetsDir: "assets",
    outDir: "static",
    rollupInputOptions: {
        plugins: [
            globalsPlugin,
            builtinsPlugin,
        ]
    }
}

@underfin
Copy link
Member

This error is already fixed, please wait new version publish.

@frederikhors
Copy link

@underfin is this published? Can we try in the meantime somehow?

@underfin
Copy link
Member

@frederikhors You can have a try with link local vite.

@sujit-baniya
Copy link

@underfin How we link local vite?

@underfin
Copy link
Member

@sujit-baniya
Copy link

@underfin I'm getting this error:

image

@underfin
Copy link
Member

Please see entirely this issue.

@sujit-baniya
Copy link

@underfin I fixed the above issue with following:

import builtins from 'rollup-plugin-node-builtins';

const builtinsPlugin = { ...builtins({ crypto: true }), name: 'rollup-plugin-node-builtins' };

module.exports = {
    assetsDir: "assets",
    outDir: "static",
    rollupInputOptions: {
        preserveEntrySignatures: 'strict',
        plugins: [
            builtinsPlugin,
        ]
    }
}

But when trying to link I'm getting following error now

image

@devhyunjae
Copy link

@underfin any clues for typescript?

I just created with

npm init @vitejs/app hello --template react-ts

then vite.config.ts

import reactRefresh from '@vitejs/plugin-react-refresh';
import builtins from 'rollup-plugin-node-builtins';

import { defineConfig } from 'vite';

const builtinsPlugin = {
  ...builtins({ crypto: true }),
  name: 'rollup-plugin-node-builtins',
};

export default defineConfig({
  plugins: [reactRefresh(), builtinsPlugin],
});

But still,

App.tsx:9 Uncaught ReferenceError: require is not defined

@yyx990803
Copy link
Member

You can't use require in your source code. Vite is ESM only.

@chrismcv
Copy link

I'm running into issues with this too. The globals plugin seems to break @vite/client

My config looks like:

import reactRefresh from "@vitejs/plugin-react-refresh";
import { defineConfig } from "vite";
import builtins from "rollup-plugin-node-builtins";
import globals from "rollup-plugin-node-globals";

const builtinsPlugin = {
  ...builtins({ crypto: true }),
  name: "builtins",
};
const globalsPlugin = {
  ...globals(),
  name: "globals",
};

export default defineConfig({
  plugins: [reactRefresh(), builtinsPlugin, globalsPlugin],

The error I'm getting is

22:49:44 [vite] Internal server error: Unexpected token (422:33) in /home/chris/code/other/my-vue-app/node_modules/vite/dist/client/client.js
  Plugin: globals
  File: /home/chris/code/other/my-vue-app/node_modules/vite/dist/client/client.js
  420|          const [path, query] = dep.split(`?`);
  421|          try {
  422|              const newMod = await import(
     |                                   ^
  423|              /* @vite-ignore */
  424|              base +
      at Parser.pp$4.raise (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:2757:13)
      at Parser.pp.unexpected (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:647:8)
      at Parser.pp$3.parseExprAtom (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:2196:10)
      at Parser.pp$3.parseExprSubscripts (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:2047:19)
      at Parser.pp$3.parseMaybeUnary (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:2024:17)
      at Parser.pp$3.parseAwait (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:2742:24)
      at Parser.pp$3.parseMaybeUnary (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:2008:17)
      at Parser.pp$3.parseExprOps (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:1966:19)
      at Parser.pp$3.parseMaybeConditional (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:1949:19)
      at Parser.pp$3.parseMaybeAssign (/home/chris/code/other/my-vue-app/node_modules/rollup-plugin-node-globals/node_modules/acorn/dist/acorn.js:1925:19)

@yyx990803
Copy link
Member

That's a problem in rollup-plugin-node-globals. It's very outdated and is probably using an old version of acorn to parse the code in script mode instead of module mode.

Suggestion: if you have dependencies that expects to use Node built-ins, try swapping it out with something more modern. Relying on Node built-ins in the browser is bad practice, period.

@baradhili
Copy link

That's a problem in rollup-plugin-node-globals. It's very outdated and is probably using an old version of acorn to parse the code in script mode instead of module mode.

Suggestion: if you have dependencies that expects to use Node built-ins, try swapping it out with something more modern. Relying on Node built-ins in the browser is bad practice, period.

yyx990803 I agree.. but pouchdb relies on "events" so no avoiding it...

@alex-shamshurin
Copy link

I have the same issue with reactRefresh() plugin. It inserts require into the bundle file, but it is true only for my existing project when I added Vite into it. But new project made from react-ts template does not have the issue. Vite configs are same.

image

@alex-shamshurin
Copy link

Oh, it was additional babel config in package.json from create react app

@keyvan-m-sadeghi
Copy link

keyvan-m-sadeghi commented Apr 13, 2021

@yyx990803

Suggestion: if you have dependencies that expects to use Node built-ins, try swapping it out with something more modern. Relying on Node built-ins in the browser is bad practice, period.

Your suggestion is simply not an option in some scenarios. I'm trying to build an app with js-libp2p and they use Node built-ins extensively. Writing a modern version of libp2p is out of scope for me!

I was able to get libp2p bundled and working with a simple esbuild config:

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'
import { build } from 'esbuild'

build({
    entryPoints: ['src/index.js'],
    target: 'es2020',
    bundle: true,
    outfile: 'dist/index.js',
    define: {
        global: 'globalThis'
    },
    plugins: [
        NodeGlobalsPolyfillPlugin({
            process: true,
            buffer: true,
            define: { 'process.env.NODE_ENV': '"production"' }, // https://github.com/evanw/esbuild/issues/660
        }),
        NodeModulesPolyfillPlugin()
    ],
});

The same cannot be replicated in vite because vite's config takes TransformOptions in the esbuild key as opposed to BuildOptions.

evanw/esbuild#779, evanw/esbuild#790

Is it feasible to incorporate the above solution to the problem in vite?

@rainbowsuger
Copy link

You can't use require in your source code. Vite is ESM only.

可以如何配置兼容吗?项目中引入第三方库包含require

@tangdw
Copy link

tangdw commented Apr 14, 2021

You can't use require in your source code. Vite is ESM only.

可以如何配置兼容吗?项目中引入第三方库包含require

开发环境都好好的,不知道是不是要配置Rollup参数,实在不行构建还是用webpack,vite只用来本地开发

@Easy-Cloud-in
Copy link

How to config vite.js to use node_module libraries in svelte-kit.

I installed npm install locomotive-scroll

and called it in .svelte file like this

import LocomotiveScroll from 'locomotive-scroll';

I get the following error:

ReferenceError: document is not defined
at /node_modules/locomotive-scroll/dist/locomotive-scroll.esm.js:255:7
at instantiateModule (E:\ec-website\svelte-next\website\node_modules\vite\dist\node\chunks\dep-66eb515d.js:69030:166)

@Shinigami92
Copy link
Member

@Easy-Cloud-in This issue is already closed. You may ask questions in Vite Land or your can open a new discussion on https://github.com/vitejs/vite/discussions.

@bstro
Copy link

bstro commented Apr 24, 2021

Leaving this clue here for anyone who's stumbling into similar problems. https://github.com/snowpackjs/rollup-plugin-polyfill-node

@vito-bogdanov
Copy link

That's a problem in rollup-plugin-node-globals. It's very outdated and is probably using an old version of acorn to parse the code in script mode instead of module mode.

Suggestion: if you have dependencies that expects to use Node built-ins, try swapping it out with something more modern. Relying on Node built-ins in the browser is bad practice, period.

That's a problem in rollup-plugin-node-globals. It's very outdated and is probably using an old version of acorn to parse the code in script mode instead of module mode.

Suggestion: if you have dependencies that expects to use Node built-ins, try swapping it out with something more modern. Relying on Node built-ins in the browser is bad practice, period.

I'm trying to use Twilio Client JS SDK and it relies on node built-ins. There is nothing i can swap it for. How can i make it work ?

@DavidWells
Copy link

I'm also seeing "ReferenceError: require is not defined" error in the built output from a dependency the app is using https://github.com/graphql/graphiql. Everything is modern JS except for this dep. Is there a way to make commonjs modules work with vite?

image

Here is my config that is not working:

import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
import nodePolyfills from 'rollup-plugin-polyfill-node';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    reactRefresh(),
  ],
  build: {
    rollupOptions: {
      plugins: [nodePolyfills()],
    },
  },
})

The build is super fast! But my app doesn't work 😅

Any suggestions would be very helpful ❤️

@github-actions
Copy link

This issue has been locked since it has been closed for more than 14 days.

If you have found a concrete bug or regression related to it, please open a new bug report with a reproduction against the latest Vite version. If you have any other comments you should join the chat at Vite Land or create a new discussion.

@github-actions github-actions bot locked and limited conversation to collaborators Jul 16, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug: upstream Bug in a dependency of Vite
Projects
None yet
Development

Successfully merging a pull request may close this issue.