I'm trying to publish and consume typescript only library(w/o dist
folder with compiled .js
files)
I created simple library:
src/test/index.ts:
export const test = 42;
src/index.ts:
import {test} from "./test";
export {
test
};
package.json:
{
"name": "test",
"version": "1.0.0",
"type": "module",
"main": "src/index.ts"
}
and published it to local npm registry.
Next, I created simple app where I installed this library as dependency.
src/index.ts:
import {test} from "test"
console.log(test);
package.json:
{
"name": "foo",
"version": "1.0.0",
"type": "module",
"main": "src/index.ts",
"scripts": {
"start": "node --experimental-specifier-resolution node --loader ts-node/esm src/index.ts"
},
"dependencies": {
"test": "^1.0.0",
"ts-node": "^10.4.0"
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"target": "esnext",
"sourceMap": true
}
}
When I run it via npm run start
I got TypeError [ERR_INVALID_RETURN_PROPERTY_VALUE]: Expected string to be returned for the "format" from the "loader getFormat" function but got type object.
CodePudding user response:
Why it happens
The issue is that ts-node
won't transpile your node_modules
folder.
Solution
So you need to explicitly tell ts-node
to handle your lib.
In your case you have to change your start
command in the root of the project from
node --experimental-specifier-resolution node --loader ts-node/esm src/index.ts
to something like (to transpile ALL node_modules
. Be careful, it's kinda bad practice)
set TS_NODE_IGNORE='' && node --experimental-specifier-resolution node --loader ts-node/esm src/index.ts
or a little bit better - with cross-env
cross-env TS_NODE_IGNORE='' node --experimental-specifier-resolution node --loader ts-node/esm src/index.ts