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}
9Then 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';
4Setup package.json export fields with Nx
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  "nx": {
4    "targets": {
5      "build": {
6        "executor": "@nx/js:tsc",
7        "options": {
8          "main": "packages/my-awesome-lib/src/index.ts",
9          "additionalEntryPoints": [
10            "packages/my-awesome-lib/src/foo.ts",
11            "packages/my-awesome-lib/src/bar.ts"
12          ],
13          "generateExportsField": true
14        }
15      }
16    }
17  }
18}
19When building the library, the @nx/js:tsc executor automatically adds the correct exports definition to the resulting package.json.
Compile to Multiple Formats
You can also compile to multiple formats, if you switch to using the @nx/rollup:rollup executor. Read all the details here.