简体   繁体   中英

Making a local Javascript library - Do I have to publish an NPM package?

I have some javascript utility functions that I would like to be able put in a central folder and reference from different projects.

It seems I cant import functions from outside the src file in of my project.

Do I have to publish an NPM package? Do I have to duplicate the code in each project?

Am using javascript/node + vscode.

thanks

You can use Lerna for dividing projects into multiple packages locally. It uses the same node_modules and can be deployed to NPM anytime.

To create a local (unpublished) library package

  1. Create a 'my-library' folder. Include source code, exporting any desired functions. Folder must include the 'package.json' file generated by npm init

  2. cd into the folder of the project that needs to use your library. Run npm install --save local/path/to/my-library .
    The --save will add the package to your dependencies in the project's package.json file, as it does with 3rd party published packages. It will also add a copy of the source code to the node modules folder of the project, as always.

  3. import/require the package as you would normally, from any project. For example import { myFunction } from "my-library"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM