Question
Why does importing from a linked local NPM pacakage (built as an ES module) using the pacakge name works when the pacakge.json has the "main" property, but fails when it has the "module" property?
Setup
More spicifically, if we have the following setup:
exporter: A Node.js package which is an ES module thatexports something (e.g., usingexport default).importer: A Node.js module that tries toimportwhatexporterexports, usingimport something from 'exporter'.- Using
npm linkto locally linkexportertoimporter.
Then:
- The setup runs successfully if
exporter'spackage.jsonuses themainproperty. - The setup run fails if
exporter'spackage.jsonuses themoduleproperty.- This failure can be "fixed" by using
import something from 'exporter/dist/bundle.js', but that's unacceptable.
- This failure can be "fixed" by using
Why is that? I guess I'm doing something wrong?
- For some more info about this setup, see my other question
Code
exporter
|- webpack.config.js
|- package.json
|- /src
|- index.js
|- /dist
|- bundle.js
webpack.config.js:
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default {
mode: "development",
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
library: {
type: "module",
},
},
experiments: {
outputModule: true,
},
};
package.json:
{
"name": "exporter",
"version": "1.0.0",
"main": "dist/bundle.js", <-- *** NOTE THIS LINE ***
"scripts": {
"build": "webpack"
},
"devDependencies": {
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0"
},
"type": "module"
}
index.js:
function util() {
return "I'm a util!";
}
export default util;
importer
|- package.json
|- /src
|- index.js
package.json
{
"name": "importer",
"version": "1.0.0",
"type": "module"
}
index.js
import util from 'exporter';
console.log(util());
Then:
- Linking:
⚡ cd exporter
⚡ npm link
⚡ cd importer
⚡ npm link exporter
- Executing:
⚡ node importer.js
I'm a util!
However, if exporter's package.json is changed to:
{
"name": "exporter",
"version": "1.0.0",
"module": "dist/bundle.js", <-- *** NOTE THIS LINE ***
"scripts": {
"build": "webpack"
},
"devDependencies": {
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0"
},
"type": "module"
}
Then:
- Executing:
⚡ node importer.js
Fails:
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'importer\node_modules\exporter\' imported from importer\src\index.js
But Why?