#Export React Wrappers as CommonJS and ES Modules

1 messages · Page 1 of 1 (latest)

keen escarp
#

This is probably relatively easy but this is my first time create a package and using Stencil so I wondered if anyone could shed some light on how to bundle React Wrappers using CommonJS (CJS) and ES Modules (ESM)?

I've followed the docs to create React Wrappers from Web Components - https://stenciljs.com/docs/react. When consuming these components as internal packages within my monorepo everything behaves nicely but when I publish these to npm and consume within the same NextJS app I'm getting an error stating:

../node_modules/@orgName/react-widgets/dist/index.js:1
betting-analysts:dev: export * from "./components/stencil-generated";
betting-analysts:dev: ^^^^^^
betting-analysts:dev:
betting-analysts:dev: SyntaxError: Unexpected token 'export'

I assume this is due to the package needing to export CJS as well as ESM but I'm not able to find anything in the docs and wondered if anyone could shed some light on the best approach for this.

stone quiver
#

you probably want to use a bundler (e.g. rollup) to output the different types.

So something like e.g.

tsconfig.json

{
  ...
  "lib": ["dom", "es2020"],
  "module": "es2015",
  "outDir": "dist-transpiled",
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ],
  ...
}```

`rollup.config.js`

export default {
input: 'dist-transpiled/index.js',
output: [
{
dir: 'dist/',
entryFileNames: '[name].esm.js',
chunkFileNames: '[name]-[hash].esm.js',
format: 'es',
sourcemap: true
},
{
dir: 'dist/',
format: 'commonjs',
generatedCode: {
constBindings: true,
},
sourcemap: true
}
],
};

Then your `package.json` tasks might look something like

...
"compile": "npm run tsc",
"bundle": "rollup",
"build": "npm run compile && npm run bundle"
...```

keen escarp
#

That's really helpful thanks @stone quiver. Making some progress with this now but I assume there's a problem with the ts config as I'm getting an error in the bundle stage now as cannot resolve in import

Could not resolve './components/stencil-generated' from dist-transpiled/index.js
stone quiver
keen escarp
#

Thanks again, I'll do some more digging

keen escarp
#

For anyone that faces a similar issue in the future I resolved this by removing the tsc compile step and doing this all within rollup.config.js:

const typescript = require("@rollup/plugin-typescript");

module.exports = {
  input: "lib/index.ts",
  output: [
    {
      dir: "dist/",
      entryFileNames: "[name].esm.js",
      chunkFileNames: "[name]-[hash].esm.js",
      format: "es",
      sourcemap: true,
    },
    {
      dir: "dist/",
      format: "commonjs",
      generatedCode: {
        constBindings: true,
      },
      sourcemap: true,
    },
  ],
  plugins: [typescript()],
};