I've stumbled across an issue while using NPM 7 workspaces and Babel where I can't wrap my head around the best way to be able to import from src/ during development but use dist/ during production.
Apologies for my awful explanation, I'll just do an example (this excludes config files and such for brevity):
My project structure is like so:
- /
- lambdas/lambda-a
- src/
- package.json
- packages/package-a
- src/
- package.json
- package.json
I have my main field in packages/package-a/package.json like so:
{
...
"main": "src/index.js",
...
}
Which means I can import stuff from packages/package-a just fine in lambdas/lambda-a/src/index.js:
import { thing } from '<package-a>'
However, by having the main field pointing to src/index.js, this isn't going to work in production, and if I change the main field to dist/index.js I can no longer import in lambdas/lambda-a during development without running a build after every change.
Does anyone have a solution for this? Or, more likely, can anyone point out where I'm being a muppet?
The workaround I use is to replace src/index.js before building and replacing it again after building/packing is done. This is neither elegant nor "how you should do it" (AFAIK), but it works for me in a small project.
I use npe because it's lightweight but there are similar (or more powerful) packages out there.
Example (packages/package-a/package.json):
...
"devDependencies": {
"npe": "^1.1.4"
},
"scripts": {
"build:before": "npe main dist/index.js'",
"build": "(npm run build:before) && (if exist dist rmdir /s /q dist) && (babel src -d dist --copy-files) && (npm pack) && (npm run build:after)",
"build:after": "npe main src/index.js",
},
...
But I'm also still searching for a more "official" way...