Reputation: 6026
I maintain a library that has has a /dist folder with versions for CommonJS, ES6 modules, and direct <script>
loading.
The package.json file is configured to identify each version:
"type": "module",
"main": "dist/pretty-print-json.umd.cjs",
"module": "dist/pretty-print-json.esm.js",
"browser": "dist/pretty-print-json.min.js",
When the library is installed:
$ npm install pretty-print-json
and imported:
import { prettyPrintJson } from 'pretty-print-json';
into a project with webpack, IDEs correctly interpret the ES6 module version plus the TypeScript declaration file (dist/pretty-print-json.d.ts).
However, the build process fails:
./src/app/app.component.ts:74:13-35 - Error: export 'prettyPrintJson' (imported
as 'prettyPrintJson') was not found in 'pretty-print-json' (module has no
exports)
The ES6 module version has an export
statement:
export { prettyPrintJson };
After a bunch of experiments with a simple Angular project, I figured out that webpack is using the "browser"
version instead of the "module"
version.
How do you configure a library so that webpack correctly picks up the "module"
version without breaking support for the other versions?
Upvotes: 1
Views: 561
Reputation: 501
The browser
field takes priority over module
and main
if your target is the browser.
I found this solution for your problem:
{
"name": "main-module-browser",
"main": "dist/index.js",
"module": "dist/index.esm.js",
"browser": {
"./dist/index.js": "./dist/index.browser.js",
"./dist/index.esm.js": "./dist/index.browser.esm.js"
}
}
Upvotes: 1