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:
{ "exports": { "./package.json": "./package.json", ".": "./src/index.js", "./foo": "./src/foo.js", "./bar": "./src/bar.js" }}Then people can access code in your library through any of the provided entry points.
import myLib from 'my-lib';import foo from 'my-lib/foo';import bar from 'my-lib/bar';Setup package.json export fields with Nx
Section titled “Setup 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:
{ "name": "my-awesome-lib", "nx": { "targets": { "build": { "executor": "@nx/js:tsc", "options": { "main": "packages/my-awesome-lib/src/index.ts", "additionalEntryPoints": [ "packages/my-awesome-lib/src/foo.ts", "packages/my-awesome-lib/src/bar.ts" ], "generateExportsField": true } } } }}{ "name": "my-awesome-lib", "targets": { "build": { "executor": "@nx/js:tsc", "options": { "main": "packages/my-awesome-lib/src/index.ts", "additionalEntryPoints": [ "packages/my-awesome-lib/src/foo.ts", "packages/my-awesome-lib/src/bar.ts" ], "generateExportsField": true } } }}When building the library, the @nx/js:tsc executor automatically adds the correct exports definition to the resulting package.json.
Compile to Multiple Formats
Section titled “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.