-1

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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
xabra
  • 139
  • 2
  • 11
  • 2
    No, you absolutely do not have to publish to npm to use a library module in multiple projects. Read the documentation of your dependency management tool. If you're not using one, you're not using npm anyway. – Bergi Jan 03 '21 at 06:58
  • Hi Bergi, I do certainly use NPM to install various public NPM packages. And I do have a package.json file as part of my project. I dont have another dependency management tool. What do you recommend? – xabra Jan 03 '21 at 07:04
  • 1
    If you're using `npm` (which you had not stated in your question), see https://stackoverflow.com/q/15806241/1048572 https://stackoverflow.com/q/8088795/1048572 https://stackoverflow.com/q/14381898/1048572 etc – Bergi Jan 03 '21 at 07:11
  • Thank you, Bergi. Sorry if I wasnt clear. The references you provided https://stackoverflow.com/q/15806241/1048572 answered my question. I'll add a little more detail below in an answer – xabra Jan 03 '21 at 09:21

2 Answers2

2

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"

xabra
  • 139
  • 2
  • 11
0

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

JustRaman
  • 1,101
  • 9
  • 11