Linking a Package as a Lerna Package Dependency for Development - javascript

The structure of my project is as follows:
packages/
client/
package.json
server/
package.json
shared/
package.json
lerna.json
package.json
The package.json file of client contains the following dependencies:
{
"name": "#my-project/client",
"dependencies": {
// ...
"#my-project/shared": "*",
"cool-components": "^1.0.0',
// ...
}
}
#my-project/shared is the package name of the packages/shared directory.
I am willing to use npm link to develop the cool-components library, and to use npm link to use its code within #my-project/client.
Currently, I tried to run:
cd packages/client
npm link cool-components
And for unlinking:
npm unlink cool-components
But, I get an error claiming that #my-project/shared is not in the NPM registry.
This is absolutely understandable; When I run NPM commands in the scope of #my-project/client, it is not familiar with its sibling packages, and it tries to look for this package in the registry. This is the reason we should use lerna add in the root instead of npm install within each package.
Even though I understand the cause, I couldn't find a proper way to use npm link to develop another package while using it within my Lerna monorepo.

You add #my-project/shared dependency to #my-project/client with:
// this creates link between packages
lerna add #my-project/shared --scope=#my-project/client
Now if you check node modules inside #my-project/client you should see
#my-project/shared.
If you want to access a dependency in your node package, you use
require.resolve:
// require.resolve will get you the absolute path
const packagePath = require.resolve("#my-project/build/index.js");
// to use the this package, for exampe in express.static
// path.dirname will give you path until build directory
// so you are going to serve up that folder
app.use(express.static(path.dirname(packagePath)));
in client side, importing module from node modules path should work without any configuration. If it does not, try to resolve the node modules path to absolute path.

Related

Remove dependency from a production build

I am trying to exclude AWS dependencies which I use for local testing from my server build, as they are quite heavy. How would you approach this with Javascript?
"dependencies": {
"aws-sdk": "^2.639.0"
}
I am using UmiJS, which uses Webpack underneath.
I am coming to from a Java world. In Java to achieve that, one would simply mark this dependency as 'test', so that it wouldn't be added to the main package
To add an entry to the "dependencies" attribute of a package.json file, on the command line, run the following command:
npm install <package-name> [--save-prod]
To add an entry to the "devDependencies" attribute of a package.json file, on the command line, run the following command:
npm install <package-name> --save-dev

Installing a private package in an Angular 8 project

I have a private package on the file system that I'm trying to install in an Angular 8 project. So far with non-angular projects, this has worked fine. From the root of the Angular project I do:
npm i -S ../the-other-project-dependency/dist
The error message is:
npm ERR! Could not install from "../the-other-project-dependency/the-other-project-dependency" as it does not contain a package.json file.
The part of this that is true is that the-other-project-dependency does not contain a package.json file.
The package.json file is in ../the-other-project-dependency/dist. Specifically, it is in the dist directory.
So I'm not sure if NPM is saying that the dist directory should be named the-other-project-dependency?
I tried renaming dist to the-other-project-dependency and now it gets passed that error, but it gives an error for another private project dependency:
Specifically it says:
`the-other-project-dependency/yet-another-private-dependency` could not be installed as it does not contain a `package.json` file.
So it looks as if NPM does not understand how to work with locally installed packages. In this last case it seems as if it's saying the yet-another-private-package-dependency should be laid out as a sibling of the-other-project-dependency and it's not reading the file system path to that dependency.
I assumed per this post that using local file deps should just work.
Update
I think it's a bug in NPM. I filed a report here
Resolution
Was able to get it working using yarn, but I had to remove the local private packages and reinstall them with yarn, as yarn uses a slightly different path string for local dependencies.

How to create a local module in TypeScript

I have created in folder src/modules/my-module/ which has package.json and defined the main file which exports everything we need.
I can import from it now import {A} from '../../modules/my-module'
I want to change the syntax into import {A} from 'my-module' and I have a few reasons for it:
When I move the module to another folder, I do not want to change all the code calling this module.
Later, I would like to have the possibility to move the module to a separate repository as the npm package and reuse it in multiple projects. I do not want to change all calling code later.
I have managed to compile it by adding to tsconfig.json
"paths": {
"my-module": ["src/modules/my-module"]
}
But I can't run the result via node.js as the node can't find the module. Is there any way to use non-realtive module reference in such scenario.
TS doesn't convert that "my-module" when transpiling your ts files to js.
Using module-alias package might solve your problem.
Add this configuration below into package.json:
"_moduleAliases": {
"my-module": "<your_build_folder>/modules/my-module"
},
And this code on first line of your main file (server.ts/index.ts)
import 'module-alias/register';
By the sounds of it, what you're wanting to do is package up your local my-module so that it can be used in the same way you'd install and use a package from the npm registry.
When you're doing local development, its easy to configure a dependency to reference to your module as a file path - though you need to have your typescript transpiled for it to work in your case.
Here's the method I'm using for local development, in an environment where we have many utility modules for a microservices architecture. I package the module into an archive and install it using npm install:
Use npm pack to package the module into a .tgz. Our package.json defines the target directory to be packaged, and the build script performs the transpile into the target (obviously adjust for your needs):
...
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "npx babel src --out-dir dist --extensions .ts,.tsx,.js --ignore **/*.test.ts,**/*.test.tsx",
...
Run npm pack and install the generated package in your application
/my-module/> npm pack
/my-module/> cd ../my-app
/my-app/> npm install --save ../my-module/my-module-0.0.1.tgz
Or as an all-in-one (builds tgz in my-app dir):
/my-app/> && npm pack ../my-module && npm i -s my-module-0.0.1.tgz
Once you're done with development, you'll probably want to publish your module in a way that its available to your project(s) on deployment.
Your options are along the lines of:
Publish to your local system using npm link
Publish to a private registry
Publish to the npm registry (as either a public or private module)
Here's a good resource for these options: https://medium.com/#debshish.pal/publish-a-npm-package-locally-for-testing-9a00015eb9fd
Add local module as dependency to package.json (in the root of your project):
"dependencies": {
"my-module": "file:src/modules/my-module",
...
}
Configure your typescript settings like here #tsconfig/recommended
Run npm install my-module in your root folder
Then you can do:
import {A} from 'my-module'
You can transpile your external local project (reference project) since Typescript 3 in July 2018.
See: How to share code between TypeScript projects?

How to verify an object instance? instanceof and ....prototype.isPrototypeOf(...) are not reliable [duplicate]

Whenever I make projects, I have to download all dependencies of node modules. Without copying the node_modules, Is there anyway to share the central node_modules in multiple projects?
like the followings, I have to run many commands every time..
npm install gulp-usemin
npm install gulp-wrap
npm install gulp-connect
npm install gulp-watch
npm install gulp-minify-css
npm install gulp-uglify
npm install gulp-concat
npm install gulp-less
npm install gulp-rename
npm install gulp-minify-html
You absolutely can share a node_modules directory amongst projects.
From node's documentation:
If the module identifier passed to require() is not a native module,
and does not begin with '/', '../', or './', then node starts at the
parent directory of the current module, and adds /node_modules, and
attempts to load the module from that location.
If it is not found there, then it moves to the parent directory, and
so on, until the root of the file system is reached.
For example, if the file at '/home/ry/projects/foo.js' called
require('bar.js'), then node would look in the following locations, in
this order:
/home/ry/projects/node_modules/bar.js /home/ry/node_modules/bar.js
/home/node_modules/bar.js /node_modules/bar.js
So just put a node_modules folder inside your projects directory and put in whatever modules you want. Just require them like normal. When node doesn't find a node_modules directory in your project folder, it will check the parent folder automatically. So make your directory structure like this:
-myProjects
--node_modules
--myproject1
---sub-project
--myproject2
So like this, even your sub-project's dependencies can draw on your main node_modules repository.
One drawback to doing it this way is you will have to build out your package.json file manually (unless someone knows a way to automate this with grunt or something). When you install your packages and add the --save arg to an npm install command it automatically appends it to the dependencies section or your package.json, which is convenient.
Try pnpm instead of npm.
pnpm uses hard links and symlinks to save one version of a module only ever once on a disk.
If you have npm installed, you can install in your terminal with:
npm install -g pnpm
To update your existing installations (and sub-directories) use:
pnpm recursive install
Or use the shorthand command (leave off -r if you need to target only one directory)
pnpm -r i
One helpful note: You may find some rare packages don't have all their dependencies defined. They might rely on the flat node_modules file directory structure of npm or yarn installs. If you run into issues of missing dependencies, use this command to hoist all the sub dependencies into a flat-file structure:
pnpm install --shamefully-hoist
It's best to avoid using the --shamefully-hoist flag as it defeats the purpose of using pnpm in the first place, so try using the command pnpm i your-missing-package first (See pnpm FAQ).
I found a trick, just take a look at the Symbolic Links (symlinks) on Windows or Linux, it is working just like shortcuts but more powerful.
Simply you need to make a Junction for your node_modules folder anywhere you want. The junction is nothing but a short cut to your original node_modules folder. Create it inside your project folder where the actual node_modules would have been created if used npm install.
To achieve this you need at least one node_modules real folder then make a Junction to it in the other projects.
On Windows, you can either use the Command Prompt, or use an application. Using the Command Prompt gives you a bit more control, using an application is easier I suggest Link Shell Extension.
Main directory should look like this
node_modules
Project 1
Project 2
Project 3
Project 4
just open the file Project 1/.angular-cli.json
change the schema
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
to
"$schema": "./../node_modules/#angular/cli/lib/config/schema.json"
and don't forget to create node_modules empty folder inside your project directory
See also npm v7.0.0's support for workspaces
RFC
https://github.com/npm/rfcs/blob/latest/implemented/0026-workspaces.md
Documentation
https://docs.npmjs.com/cli/v7/using-npm/workspaces
By looking at some articles it seems that Lerna
is a good tool for managing multiple projects inside a single directory (monorepo). It supports modules sharing without duplicating the entire packages in every folder and commands to install them in multiple projects.
Javascript monorepos
Monorepos by example
Building large scale apps in a monorepo
pnpm is also a simple and efficient tool, which doesn't duplicate those modules which are already installed for other projects.
Let's assume that having a single node_modules it should contain all the packages for all applications. thus your apps will also share most of the unique package.json entries (just the name should change)
my idea would be to have a single root and multiple src level as below
root\package.json
root\node_modules
root\\..
root\app1\src\\..
root\app2\src\\..
the only issue you might face would be having a backup of json (or tsconfig) for any app and restore them when you work on it or setup your startup scripts to serve any app

Installing a local module using npm?

I have a downloaded module repo, I want to install it locally, not globally in another directory?
What is an easy way to do this?
you just provide one <folder> argument to npm install, argument should point toward the local folder instead of the package name:
npm install /path
From the npm-link documentation:
In the local module directory:
$ cd ./package-dir
$ npm link
In the directory of the project to use the module:
$ cd ./project-dir
$ npm link package-name
Or in one go using relative paths:
$ cd ./project-dir
$ npm link ../package-dir
This is equivalent to using two commands above under the hood.
Since asked and answered by the same person, I'll add a npm link as an alternative.
from docs:
This is handy for installing your own stuff, so that you can work on it and test it iteratively without having to continually rebuild.
cd ~/projects/node-bloggy # go into the dir of your main project
npm link ../node-redis # link the dir of your dependency
[Edit] As of NPM 2.0, you can declare local dependencies in package.json
"dependencies": {
"bar": "file:../foo/bar"
}
npm pack + package.json
This is what worked for me:
STEP 1: In module project, execute npm pack:
This will build a <package-name>-<version>.tar.gz file.
STEP 2: Move the file to the consumer project
Ideally you can put all such files in a tmp folder in your consumer-project root:
STEP 3: Refer it in your package.json:
"dependencies": {
"my-package": "file:/./tmp/my-package-1.3.3.tar.gz"
}
STEP 4: Install the packages:
npm install or npm i or yarn
Now, your package would be available in your consumer-project's node_modules folder.
Good Luck...
Neither of these approaches (npm link or package.json file dependency) work if the local module has peer dependencies that you only want to install in your project's scope.
For example:
/local/mymodule/package.json:
"name": "mymodule",
"peerDependencies":
{
"foo": "^2.5"
}
/dev/myproject/package.json:
"dependencies":
{
"mymodule": "file:/local/mymodule",
"foo": "^2.5"
}
In this scenario, npm sets up myproject's node_modules/ like this:
/dev/myproject/node_modules/
foo/
mymodule -> /local/mymodule
When node loads mymodule and it does require('foo'), node resolves the mymodule symlink, and then only looks in /local/mymodule/node_modules/ (and its ancestors) for foo, which it doen't find. Instead, we want node to look in /local/myproject/node_modules/, since that's where were running our project from, and where foo is installed.
So, we either need a way to tell node to not resolve this symlink when looking for foo, or we need a way to tell npm to install a copy of mymodule when the file dependency syntax is used in package.json. I haven't found a way to do either, unfortunately :(
Missing the main property?
As previous people have answered npm i --save ../location-of-your-packages-root-directory.
The ../location-of-your-packages-root-directory however must have two things in order for it to work.
package.json in that directory pointed towards
main property in the package.json must be set and working i.g. "main": "src/index.js", if the entry file for ../location-of-your-packages-root-directory is ../location-of-your-packages-root-directory/src/index.js
So I had a lot of problems with all of the solutions mentioned so far...
I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.
I also need it to work on Windows AND Unix, so sym-links aren't ideal.
Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.
so.. This is what worked well for me!
Main Project's Package.json File Snippet:
"name": "main-project-name",
"version": "0.0.0",
"scripts": {
"ng": "ng",
...
"preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
},
"private": true,
"dependencies": {
...
"#com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
...
}
This achieves 3 things:
Avoids the common error (at least with angular npm projects) "index.ts is not part of the compilation." - as it points to the built (dist) folder.
Adds a preinstall step to build the referenced npm client package to make sure the dist folder of our dependent package is built.
Avoids issues where referencing a tar.gz file locally may be cached by npm and not updated in the main project without lots of cleaning/troubleshooting/re-building/re-installing.
I hope this is clear, and helps someone out.
The tar.gz approach also sort of works..
npm install (file path) also sort of works.
This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)
======
UPDATE:
======
There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.
As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.
First:
For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.
As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:
"scripts": {
"build": "ng-packagr -p ng-package.json",
"package": "npm install && npm run build && cd dist && npm pack"
},
And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:
"scripts": {
"preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
},
Second
Reference the built tgz npm package from your main project!
"dependencies": {
"#com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
...
}
Third
Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.
If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348
for now, just update the:
"version": "1.0.0-build5",
In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:
"dependencies": {
"#com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
...
}
You get used to it. Just update the two package.json files - version then the ref to the new filename.
Hope that helps someone...
I came across different solution than above while installing custom build package for CKEditor5.
So I uploaded package to app root directory, than:
npm add file:./ckeditor5
In my package.json package is listed as a file:
"ckeditor5-custom-build": "file:ckeditor5",
I think this answer could be relevant to the topic on how to add local package.
For installing local module / package, that not yet on npm or you are developing an npm package and want to test it locally before publishing it. You can try this -
npm i yalc -g
Go to the module/package folder then -
yalc publish
Your packakge is ready to use, now go the project you want to install it -
yalc add <Your package name>
Package will be installed to you project. If you want to remove it -
yalc remove <Your package name>
For more recent versions of npm (I'm using 8.1.3 under macOS Big Sur), the sequence of commands is even easier...
cd /path-where-your-local-project-is/
npm init
This will ask you for some data related to your project and properly initialises your project.json file.
Once that is done, you can install additional modules with:
cd /path-where-your-local-project-is/
npm install --save-dev some-npm-module .
That's all you need!
Note: I believe that the trailing dot is not necessary if you're inside the project directory, but I also think that it doesn't hurt to add it :-)
(I wonder why the official docs still don't explain this...)

Categories

Resources