Answer 1
This answer does not require using a runtime flag --es-module-specifier-resolution=node
at execution time
However, you have to modify your ts source code, which is a pain if there is are a lot of files. And, the modified files will no longer compile in "commonjs" mode, if you want to go back or use dual "commonjs"/"module" modes.
Modify your tsconfig.json to ensure at least these setting versions:
compilerOptions:{
"lib": ["es2020"],
"module": "ES2022",
"moduleResolution": "node",
"target": "es2022",
}
Works with typescript 4.6.3. (Note sure about 4.6.1 or lower).*
Modify index.js
import {urls} from "#helpers";
Modify package.json
"imports": {
"#helpers": "./helpers.js"
}
The leading "#" is mandatory
Answer 2
In addition to not requiring the node runtime execution flag, this answer also satisifes:
- does not require changing your
*.*ts
source code (thus leaving it compilable under commonjs if you ever chose to do so(*note))
- In case you are producing a library, it produces output which can be consumed by either "commonjs" or "module" clients.
(*note) When using rollup, inline maps are required - so there may sometimes be advantage to using commonjs during development and switching to "module" for release.
First modify package.json, create rollup.config.js, and then perform a post tsc action using rollup.
package.json
...
"exports":{
"require":"./index.cjs",
"import":"./index.js"
},
"types": "./index.d.ts",
"type": "module" // you already had this
rollup.config.js
// import resolve from "@rollup/plugin-node-resolve";
import dts from "rollup-plugin-dts";
import commonjs from "@rollup/plugin-commonjs";
import * as path from "path";
import pkg from "./package.json";
export default [
{
input: "index.js",
external:[], // you may quash 'unresolved' warning by adding here
output: [
{ file: pkg.exports.require, format: "cjs" },
{ file: pkg.exports.import, format: "es" },
],
plugins: [
commonjs(),
],
},
{
input: "./index.d.ts",
output: [
{ file: pkg.types, format: "es" },
],
plugins: [dts()],
},
];
Call tsc
then rollup
:
npx tsc
npx rollup -c