developit / microbundle

📦 Zero-configuration bundler for tiny modules.
https://npm.im/microbundle
MIT License
8.04k stars 362 forks source link

Help with bundling a react library for nextjs #913

Closed mario-symphony closed 2 years ago

mario-symphony commented 2 years ago

Current setup

  "type": "module",
  "source": "src/index.tsx",
  "main": "dist/index.umd.js",
  "module": "dist/index.es.js",
  "style": "dist/index.css",
  "types": "dist/index.d.ts",
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "microbundle --jsx 'React.createElement' --jsxImportSource react --globals react/jsx-runtime=jsx --format umd,es"
  },

And current problem

Server Error
ReferenceError: self is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

I've looked at this bit here that says that you guys are forcefully removing globalThis self which is causing issues with nextjs.

I've been struggling for the past two days but I'm lacking some fundamentals around bundling and all of these esm/cjs/umd formats to be able to fix this.

Would anyone be able to adjust my package.json to be able to write React + TS library that can be consumed in NextJS app?

rschristian commented 2 years ago

"type": "module" with UMD as your main is likely the issue, and that doesn't make much sense. Don't label your package as being ESM when it's not.

Try removing "type": "module".

mario-symphony commented 2 years ago

This seems to fix it. Thanks.

rschristian commented 2 years ago

Just to add a bit more information, "type": "module" signals to Node (and most bundlers nowadays) that the .js file extension should be treated as ESM, and that .cjs is used when you're referring to a CJS module. As you've set this, your UMD is loaded as ESM when it's not.

A bit of a trick here is the "module" field, which is ignored by Node and only used by bundlers. Because of this, it can get away with (and often needs to be) .js even though it is fact ESM. It doesn't play by Node's rules as Node does not acknowledge it.