I've created an NX workspace using
npx create-nx-workspace --name libtest --preset angular --style scss --appName demo --nxCloud false
code libtest
Then I created a TypeScript library using
nx add @nrwl/node
nx generate @nrwl/js:library --name=example-qr-code --buildable --publishable --import-path @example/qr-code
This library contains an example function by default:
export function exampleQrCode(): string {
return 'example-qr-code';
}
First, to be sure, update the workspace to the latest NX again:
nx migrate latest
Open the package.json and restore the ^
and ~
.
Run
npm update
npx nx migrate --run-migrations
Now I can use this function in my application
import { Component } from '@angular/core';
import { exampleQrCode } from '@example/qr-code';
@Component({ ... })
export class AppComponent {
constructor() {
this.title = exampleQrCode();
}
title = 'demo';
}
Obviously, nothing yet happens with the title. So I opened the app.component.html
and replaced everyting with
{{ title }}
And start the application:
npm start -- --open
There's still some scripts missing from the root package.json
:
{
...,
"scripts": {
"ng": "nx",
"nx": "nx",
"postinstall": "node ./decorate-angular-cli.js && ngcc --properties es2020 browser module main",
"start": "nx serve",
"build": "nx build",
"test": "nx test"
},
...
}
Now you can build the entire workspace (or more precisely, main project with dependencies) using
npm run nx run-many -- --target=build --projects=demo --configuration=production
After this you can see the build result in the dist
folder:
I'm able to run the project from the NX workspace successfully, but I'm unable to create a new angular project and use this library in it.
./node_modules/@example/ng-qr-code/fesm2020/example-ng-qr-code.mjs:6:0-53 - Error: Module not found: Error: Can't resolve '@example/qr-code' in 'C:\repos\qrtest\node_modules@example\ng-qr-code\fesm2020'
However, when I open the package.json
file from the node_modules/@example/qr-code
and change from
{
"main": "./src/index.ts",
...
}
to
{
"main": "./src/index.js",
...
}
manually, then everything starts working.
Did anyone else experience this? How can I have NX generate a package.json
with the main
field set to a js file?
Repository is hosted here
Ah never mind... Just changing the main
field in the source package.json
to ./src/index.js
does the trick.
The file doesn't really have to exist at build time...