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

Bundling SSR Modules using CommonJS exports alias results in ReferenceError: exports is not defined #2579

Closed
GrygrFlzr opened this issue Mar 18, 2021 · 45 comments · Fixed by #8430
Labels
feat: ssr p4-important Violate documented behavior or significantly improves performance (priority)

Comments

@GrygrFlzr
Copy link
Member

GrygrFlzr commented Mar 18, 2021

Describe the bug

When importing an SSR module, if

  • it uses the exports alias instead of module.exports,
  • ssr.noExternal is declared with the module

Vite is unable to evaluate it. This can also happen with the more common module.exports, but seems to not be guaranteed.

While this behavior may seem esoteric due to modern proliferation of module.exports, this is a feature of Node since v0.1.16 and has not been deprecated. In addition, there are instances of various npm modules in the wild which use this method of exporting fields, including, but not limited to:

...and much, much, more searchable on GitHub. I believe this is also an output of some bundlers.

Reproduction

https://github.com/GrygrFlzr/vite-cjs-ssr

git clone https://github.com/GrygrFlzr/vite-cjs-ssr.git
cd vite-cjs-ssr
npm i
npm run dev

Visit http://localhost:3000 to trigger SSR, which consists of a very simple script that uses the cookie npm module.
The page will render exports is not defined and errors will show up in the server console:

6:29:45 PM [vite] new dependencies found: cookie, updating...
6:29:45 PM [vite] Error when evaluating SSR module /node_modules/cookie/index.js:
ReferenceError: exports is not defined
    at /node_modules/cookie/index.js:15:1
    at instantiateModule (C:\Users\GrygrFlzr\Documents\projects\vite-cjs\node_modules\vite\dist\node\chunks\dep-efe32886.js:68893:166)
ReferenceError: exports is not defined
    at /node_modules/cookie/index.js:13:1
    at instantiateModule (C:\Users\GrygrFlzr\Documents\projects\vite-cjs\node_modules\vite\dist\node\chunks\dep-efe32886.js:68893:166)

System Info

  • vite version: 2.1.2
  • Operating System: Windows 10 10.0.19042
  • Node version: 14.16.0
  • Package manager and version: npm 6.14.11
@GrygrFlzr GrygrFlzr changed the title SSR Modules using CommonJS exports alias results in ReferenceError: exports is not defined Importing SSR Modules using CommonJS exports alias results in ReferenceError: exports is not defined Mar 18, 2021
@techniq
Copy link

techniq commented Mar 18, 2021

@GrygrFlzr I believe I am running into this issue as well, and had posted an issue with LayerCake. I have a minimal SvelteKit repo here if it helps to troubleshoot.

@GrygrFlzr GrygrFlzr changed the title Importing SSR Modules using CommonJS exports alias results in ReferenceError: exports is not defined Bundling SSR Modules using CommonJS exports alias results in ReferenceError: exports is not defined Mar 18, 2021
@GrygrFlzr GrygrFlzr added bug: ssr p5-urgent Fix build-breaking bugs affecting most users, should be released ASAP (priority) and removed pending triage labels Mar 27, 2021
@rifler
Copy link

rifler commented Apr 2, 2021

are there any workarounds?

@bryik
Copy link

bryik commented Apr 6, 2021

are there any workarounds?

You could try importing the library via ye olde <script> in the <head> and then assign from window instead of importing. This worked for me with D3 and SvelteKit anyways.

@BetaConnector
Copy link

Same problem with faunadb.
Unfortunately if you want to stick with netlify there is no other choice.

@benmccann
Copy link
Collaborator

benmccann commented Apr 6, 2021

I believe this is also an output of some bundlers.

It turns out that Rollup creates output that uses just exports instead of module.exports so this is probably quite common to hit. A user reported this issue with apollo-link-prismic which is written in ESM but then bundled to CJS with Rollup

@anilbhattaraitoronto
Copy link

I am having exactly the same error with better-sqlite3 .

@yaquawa
Copy link
Contributor

yaquawa commented Apr 6, 2021

Can't solve the problem even using the module.exports...

@jlkiri
Copy link

jlkiri commented Apr 7, 2021

For me changing to module.exports also does not solve the problem: I get module is not defined error.

@leemove
Copy link
Contributor

leemove commented Apr 12, 2021

It looks like doesn't support commomjs

@BetaConnector
Copy link

@rifler, check out my issue:
#2862

I converted the module from cjs to esm. After that I placed the module directly into my project and removed the dependency.

This is really ugly but seems to work for rhis moment.

@GrygrFlzr, how are your plans regarding to cjs modules? Will there be a solution or is cjs just not supported?

@ggoodman
Copy link

#2890 talks about a potential, but ugly work-around.

@quantuminformation
Copy link

@ggoodman I'm not even using vite-cjs-ssr and I get this error

10:38:19 [vite] Error when evaluating SSR module /node_modules/node-timecodes/dist/index.js:
ReferenceError: exports is not defined
    at /node_modules/node-timecodes/dist/index.js:5:23```

I've seen a few issues that seem related like:
https://github.com/mhkeller/layercake/issues/41

@Jakeii
Copy link

Jakeii commented Dec 28, 2021

Another lesser used syntax module['exports'] = xyz; also seems to be affected by this issue, discovered trying to import https://github.com/infusion/Fraction.js into a sveltekit project.

@leetrout
Copy link

leetrout commented Jan 1, 2022

@crypticwasp254
Copy link

have you tried

import {* as somename} from 'module';
//tried with cookie and it worked
import * as cookie from 'cookie';

@benmccann benmccann added p3-minor-bug An edge case that only affects very specific usage (priority) and removed p4-important Violate documented behavior or significantly improves performance (priority) labels Jan 21, 2022
@marcelchastain
Copy link

marcelchastain commented Jan 30, 2022

Managed to get around a similar issue by using the vite-plugin-commonjs plugin:

// vite.config.ts
import { esbuildCommonjs, viteCommonjs } from "@originjs/vite-plugin-commonjs";
import react from "@vitejs/plugin-react";
import { UserConfig } from "vite";
import ssr from "vite-plugin-ssr/plugin";

const config: UserConfig = {
  plugins: [viteCommonjs(), react(), ssr()],
  optimizeDeps: {
    esbuildOptions: {
      plugins: [esbuildCommonjs(["@app/config"])],  // the problematic cjs module
    },
    include: ["@app/config"],  // also here
  },
};

export default config;

@benmccann benmccann added p4-important Violate documented behavior or significantly improves performance (priority) and removed p3-minor-bug An edge case that only affects very specific usage (priority) labels Jan 30, 2022
@andreataglia
Copy link

andreataglia commented Mar 30, 2022

This workaround works for me:

Inside vite.config.ts

optimizeDeps: {
    include: ['badPackage'],
},

@thewilkybarkid
Copy link

I seem to have a related problem with the fp-ts-routing library: Vite just hangs; adding it to optimizeDeps.include makes no difference; including it in ssr.noExternal sees a ReferenceError: exports is not defined error thrown.

vite build works successfully, however.

@samullman
Copy link

I was having this issue and fixed with https://github.com/originjs/vite-plugins/tree/main/packages/vite-plugin-commonjs

Working on a sveltekit project may help someone in the future

@lmiller1990
Copy link

lmiller1990 commented Jun 27, 2022

I am seeing something similar - exports is not defined. It only happens on my windows machine; not macOS or linux. The built assets are completely different.

I'll verify someone else in my company can repro on a windows machine before making an issue. The repo in question is cypress-io/cypress - cd packages/app && yarn build-prod-ui. I'm on the latest Vite (2.9.13).

Could be dup of #8800

@patak-dev
Copy link
Member

This issue was closed for vite v3, please check the latest beta. You'll need to add the dep to ssr.noExternal

@ollyde
Copy link

ollyde commented Jul 3, 2022

I can't seem to get basic node modules working on the build version, using svelte-kit build

Works on dev mode.
/// send_form.ts
import * as geoip from 'geoip-lite';

Adding

ssr: {
    noExternal: ['geoip-lite']
}

Gives the error
config.kit.ssr has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle

The https://kit.svelte.dev/docs/hooks#handle
Doesn't really explain why it's useful for this :-/

vite: {
    optimizeDeps: {
        include: ['geoip-lite']
    }
}

Doesn't, out of ideas here...

I'm amazed that something this basic is broken..

@benmccann
Copy link
Collaborator

@OllyDixon you put the config in the wrong place. It needs to go in kit.vite.ssr and not kit.ssr

I'm amazed that you broke something this basic 😉

@ollyde
Copy link

ollyde commented Jul 3, 2022

I removed all of the config and added the import like this instead import geoip from 'geoip-lite'; and it works, thanks for the reply.

@theotherdon
Copy link

Wa also able to resolve this issue by using the vite-plugin-commonjs plugin.

@github-actions github-actions bot locked and limited conversation to collaborators Jul 30, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
feat: ssr p4-important Violate documented behavior or significantly improves performance (priority)
Projects
None yet