Link to article at Medium: https://medium.com/@dimpiax/node-js-using-local-module-in-project-c6fb54bbc83a
You have several projects that use the same abstract libraries, you can hold “the same independent copy (not good) or create a private repository at npm.js.
I will share with you my experimental approach that is good in specific case.
File structure is next:
/serviceA
/serviceB
/library
Both services use same abstract classes / scripts from library, or a few of them. You can install local library as dependency simply putting local path to it.
Further examples will be with serviceA.
cd serviceA
npm i --no-save ../library
Important to not save dependency in package.json. Also npm creates alias to library, so after any changes you have a fresh version. After installing you can require your library’s dependency files as default.
Not bad, but what to do in production case?
For example, I have built a project using babel and want to add some additional files to built folder, that i will upload farther via git hook, scp or s3.
Use-case, in more details, uploading zip file to s3 and update Lambda function. There is no scenario to install dependencies inside lambda function, so need to put project as is.
Solution is to put your library by script inside build folder — not good, but works. Maybe sometime npm will support this approach by command.
Example: import syncManager from 'library/managers/syncManager'
Prepare package.json and some scripts inside.
package.json:
{
"name": "serviceA",
"version": "0.1.0",
"main": "index.js",
"config": {
"sourceDir": "src",
"buildDir": "dist",
"library": {
"name": "library",
"path": "../library"
}
},
"scripts": {
"clean": "rimraf $npm_package_config_buildDir",
"build:prod": "NODE_ENV=production npm run clean && mkdir $npm_package_config_buildDir && cp$npm_package_main package.json package-lock.json $npm_package_config_buildDir && cd $npm_package_config_buildDir && npm i",
"pack:prod": "npm run build:prod && mkdir -p $npm_package_config_buildDir/node_modules/$npm_package_config_library_name && cp -r $npm_package_config_library_path/. $npm_package_config_buildDir/node_modules/$npm_package_config_library_name/.",
},
"author": "Dima Pilipenko <dimpiax@gmail.com>",
"dependencies": {
}
}
Pay attention that dependencies
does not have an library mention.
By calling npm run pack:prod
project is being prepared for farther use.
Hope this approach is useful for someone too :)
The end.
Dear reader, if you have some proposition or question about this approach — let’s discuss in comments.
Top comments (0)