2

I have an NPM module that uses another local NPM module containing shared code. Neither of them are public, this is all local.

I import the shared module in my package.json like so:

  "my-shared": "file:../my-shared-code"

When I npm install, my-shared-code gets imported correctly, and I can import code like:

import Blah from 'my-shared/src/sharedTypes';

Problem

I have to use the word "src" in the import. However, when I build I create a build directory, which breaks all these imports!

I was wondering if I could use NPM to map the imports somehow?

Can I make it so I don't have to use the word "src" at all?

Could I just do:

import Blah from 'my-shared/sharedTypes';

and then it magically figures out whether to use the "src" or "build" dirs?

What I tried

I looked into the options for package.json, and there is a "files" property that I thought might help. However I think that just whitelists files.

I also looked into the "main" property, however I'm not "exporting a module". I just have a load of utility files that I wanna be able to import into multiple other projects.

What I'm actually trying to achieve

I'm using typescript, and I've got a front-end and a backend that both share types for certain models, but also share some utility functions.

I want my typescript/react front-end and my typescript backend to be able to import typescript files from another node_package, however it needs to know to use "src" for development and "build" when built for production.

AlexMorley-Finch
  • 6,785
  • 15
  • 68
  • 103
  • You want to use the *build files* of the other module, not the source files. Typescript will happily consume the compiled JS of the shared module (esp if .d.ts declaration files are present). – Jared Smith Nov 28 '22 at 17:40

2 Answers2

0

While it's not exactly what you're asking for, you might be looking for npm link. It's not intuitive, but it's what I use for your above situation.

npm-link is a way of registering local projects so that others can reference them. Just beware that reading the docs is important -- using it may impact your local environment in non-obvious ways (especially if you build and publish directly from your machine--versus CI/CD).

STW
  • 44,917
  • 17
  • 105
  • 161
0

In the consumer project you can use path mapping --> https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

As for the package, you can re-export using export * from './my-file' syntax, in a index.ts file (you may need one at each directory). But this is tedious if you have a lot of files. (imperfect example)

Another solution seems to make a script to copy the package.json into the dist folder and make the build there.

There is a similar discussion there: How to npm publish specific folder but as package root

Ambroise Rabier
  • 3,636
  • 3
  • 27
  • 38