Create and publish an NPM package (using NX)
Using "NX" we are going to set up a basic project with a small REACT library that you can deploy to npm.
Nx is a smart, fast, and extensible build system with first-class monorepo support and powerful integrations. (from NX docs)
(note: nx version 15.3, react 18.2.0)
The first step is to run the basic mono repo configuration of an NX project, running the following command:
Selecting the following options:
After the installation of the packages, you can enter the folder of the new project (I'm going to use vs code) :
You can run the basic project with:
Then in your browser, you will see something like this
We are ready to create our library, NX It makes it easy for us to create with a simple command (or its extension for vs code)
Why do this flags?
You can find the generated library in this path "my-library/libs/awesome-library"
(the main code is inside the src/lib/awesome-library.tsx file)
For testing purposes, we are going to import this library into our react app?
(the import is the same that we use in the importPath flag)
Run the start command you will see the new library working as a normal react component with the text "Welcome to AwesomeLibrary!"
领英推荐
We are ready to build and publish this library to npm
(you will need to have an npm account and follow the npm documentation to init session, in this case, I'm using a free account that has unlimited?Public?Packages)
Run the command and follow the instructions:
add and organization
After that add this extra configuration in the library, is needed for CJS support:
in the libs\awesome-library\project.json file, add the following options to the build:
-"skipTypeField": true,
-"format": ["esm", "cjs"],
(note this configuration is optional)
Run the command:
It will build the library in the dist folder ready to be published
(if you need to modify the organization and version change this before building the library in the package.json file)
Run the command:
(make sure that you are in the dist\libs\awesome-library folder, if you have a problem with the command, set the configuration of npm to public with "npm config set access public")
We can see the library in the npm registry (as a public package)
That's it, NX makes it really easy to create libraries! you can install it in any react project.