Define Secondary Entry Points for Typescript Packages
If you have a package where you want people to be able to access more than just the main
file, you can define an exports
property in the package.json
file. Like this:
1{
2 "exports": {
3 "./package.json": "./package.json",
4 ".": "./src/index.js",
5 "./foo": "./src/foo.js",
6 "./bar": "./src/bar.js"
7 }
8}
9
Then people can access code in your library through any of the provided entry points.
1import myLib from 'my-lib';
2import foo from 'my-lib/foo';
3import bar from 'my-lib/bar';
4
Nx helps generate other properties in the package.json
file, and you can also use Nx to maintain this property.
If you're using the @nx/js:tsc
executor, as of Nx 16.8, you can specify the additionalEntryPoints
and generateExportsField
options. Here's an example:
1{
2 "name": "my-awesome-lib",
3 "targets": {
4 "build": {
5 "executor": "@nx/js:tsc",
6 "options": {
7 "main": "packages/my-awesome-lib/src/index.ts",
8 "additionalEntryPoints": [
9 "packages/my-awesome-lib/src/foo.ts",
10 "packages/my-awesome-lib/src/bar.ts"
11 ],
12 "generateExportsField": true
13 }
14 }
15 }
16}
17
When building the library, the @nx/js:tsc
executor automatically adds the correct exports
definition to the resulting package.json
.
You can also compile to multiple formats, if you switch to using the @nx/rollup:rollup
executor.