I'm trying to make d3 v7 work in Typescript + Node environment. The previous code on d3 v6 was working fine with these configurations:
tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
}
}
and there was NO "type": "module" in package.json file.
What I've tried (step-by-step):
- Updated d3 to v7 and restarted the app; Error:
/app/dist/controllers/d3-node.js:4
const d3_1 = require("d3");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/d3/src/index.js from /app/dist/controllers/d3-node.js not supported.
Instead change the require of index.js in /app/dist/controllers/d3-node.js to a dynamic import() which is available in all CommonJS modules.
which was expected due to d3 v7 changes.
- knowing that I need to make Typescript compiler generate
importstatements instead ofrequire, I changed thetsconfig.jsonto:
{
"compilerOptions": {
"target": "ES6",
"module": "ES2020", /* <------------- */
"moduleResolution": "node",
"esModuleInterop": true,
}
}
which results in this error (as expected):
import app from '../app.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
- To solve the previous error, I added
"type": "module"topackage.json, hoping this would (finally!) solve the issue.
Basically the change caused all import statements to break; so as an example, this import:
import app from '../app'
results in:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/app/dist/app' imported from /app/dist/bin/www.js
After finding this #13422 issue on GitHub, I know that I should add .js to the end of import statements to make it work.
But the project has dozens of import statements and BTW, as discussed in the issue, it doesn't feels right to have all those .js extensions, even though we're writing Typescript.
Is there any other way to make it work without adding the .js to all the import statements?
Thanks