Node/NPM How to map import paths

Viewed 81

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.

1 Answers

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).

Related