1.0.0 • Published 1 year ago

@lidakai/react-utils v1.0.0

Weekly downloads
-
License
-
Repository
-
Last release
1 year ago

Getting Started

This is a small example repo on how to bundle a ESM library using webpack5. It was based on this blog post and the webpack documentation. It contains several branches:

How to test out this example

  1. Pick a branch.

  2. Install the node dependencies npm i.

  3. Build the bundle using webpack npm run build.

  4. Execute the local_importer.js node script node local_importer.js to see test that the bundle can be imported from inside the main package.

  5. Go into the CRA demo project. Currently the webpack5-library-example library is dynamically linked inside the package.json. You can, however, also use the npm link command.

  6. Install the node dependencies.

  7. Start the development server using npm start.

How to create a ESM library

The steps below are taken from https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c:

  • Add "type": "module" to your package.json.

  • Replace "main": "index.js" with "exports": "./index.js" in your package.json.

  • Update the "engines" field in package.json to Node.js 12: "node": "^12.20.0 || ^14.13.1 || >=16.0.0".

  • Remove 'use strict'; from all JavaScript files.

  • Replace all require()/module.export with import/export.

  • Use only full relative file paths for imports: import x from '.';import x from './index.js';.

  • If you have a TypeScript type definition (for example, index.d.ts), update it to use ESM imports/exports.

  • Optional but recommended, use the node: protocol for imports.

How to use Webpack to build a ESM library

  • Convert your webpack.config.js to a ESM module.

  • Enable the experiments.outputModule option to make sure webpack outputs ECMASCript module syntax when possible.

  • Enable output.module to make sure that javascript files are outputted as ESM modules.

  • If you want your library to be consumed by others make sure to set the output.library.type flag to module.

  • Point the package.json exports property to your outputted bundle.

  • If you want your ESM library to work with a CRA app you have to also specify the "browser": "./build/index.js", entry in your package.json. One known issue is #10933.

How to exclude externals

To see the example checkout the webpack-react-css-lodash-external branch. A guide on how to add externals can be found in the Webpack documentation. The only thing that you have to keep in mind is that when bundling a ES module the externalstype option is set to 'module' by default. If your external module therefore is a ESM module you simply use the following:

externals: {
    "lodash-es": "lodash-es",
}

If your external module is specified in a different format see the documentation.

Useful Resources

1.0.0

1 year ago