egoist / tsup

The simplest and fastest way to bundle your TypeScript libraries.
https://tsup.egoist.dev
MIT License
9.01k stars 217 forks source link

ESM output with CJS content #701

Open elrumordelaluz opened 2 years ago

elrumordelaluz commented 2 years ago

I am pretty happy using tsup for a couple of packages inside a monorepo (using turbo), but having several problems with a particular one, which fires the error described at #579, in my case, the message is:

Error: Dynamic require of "react" is not supported

Screenshot 2022-08-27 at 17 55 13

The dev and build scripts are the same for all packages, however I am noticing that for this particular one, the .mjs and .js output is pretty similar. I mean that the mjs file has the appearance to be transpiled into cjs, like in the screenshot below, when in the other packages, the same file maintains the import statements and modern structure like the input file.

Screenshot 2022-08-27 at 18 01 22

Thanks in advance!

Upvote & Fund

Fund with Polar

nitedani commented 2 years ago

Related: https://github.com/evanw/esbuild/issues/1921 https://github.com/evanw/esbuild/pull/2067

elrumordelaluz commented 2 years ago

also:

https://stackoverflow.com/questions/68423950/when-using-esbuild-with-external-react-i-get-dynamic-require-of-react-is-not-s?rq=1

and

https://github.com/evanw/esbuild/issues/1944

10Derozan commented 2 years ago

The solution is to external the other cjs packages that required react, like react-dom

glitch-txs commented 1 year ago

hey could you solve this? I'm using external react and still got the same error

MatejFacko commented 10 months ago

any update on this guys?

tsup version: 8.0.1

I am using following tsup config:

import { sassPlugin } from 'esbuild-sass-plugin';
import { defineConfig } from 'tsup';

export default defineConfig({
  entry: ['src/index.ts'],
  sourcemap: true,
  clean: true,
  bundle: true,
  dts: true,
  esbuildPlugins: [sassPlugin()],
  splitting: true,
  minify: true,
  format: ['esm', 'cjs'],
  external: ['react', 'react-dom']
});

but in App after npm install I am getting an error (index.js:1 Uncaught Error: Dynamic require of "react" is not supported)

Screenshot 2023-12-01 at 14 30 49

segevfiner commented 4 months ago

@egoist I wonder if you might want to include the workaround that some other bundlers use, but esbuild doesn't, as a plugin in tsup:

import { defineConfig } from 'tsup';

export default defineConfig({
  // *snip*
  banner(ctx) {
    if (ctx.format === "esm") {
      return {
        js: `import { createRequire } from 'module'; const require = createRequire(import.meta.url);`,
      };
    }
  },
});
segevfiner commented 2 months ago

Or maybe even as part of the shims option...

@egoist