I have the following project:
package.json:
{
"name": "ts-sequelize-node-fetch",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "main.js",
"scripts": {
"build": "tsc",
"start": "node dist/main.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/validator": "^13.6.3",
"typescript": "^4.4.3"
},
"dependencies": {
"node-fetch": "^3.0.0",
"sequelize": "^6.6.5",
"sqlite3": "^5.0.2"
}
}
tsconfig.json:
{
"compilerOptions": {
"target": "esnext",
"module": "ESNext",
"strict": true,
"moduleResolution": "node",
"outDir": "dist",
}
}
main.ts:
import fetch from "node-fetch";
import { Sequelize, DataTypes } from "sequelize";
const response = await fetch("https://google.com");
console.log(response.status);
const db = new Sequelize({
dialect: "sqlite",
storage: ":memory:"
});
console.log(DataTypes.BLOB);
try {
await db.authenticate();
console.log("DB connection established");
} catch(e) {
console.error("Unable to connect to the database");
}
When I run this (npm run build && npm start) I get the following error:
import { Sequelize, DataTypes } from "sequelize";
^^^^^^^^^
SyntaxError: Named export 'DataTypes' not found. The requested module 'sequelize' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'sequelize';
const { Sequelize, DataTypes } = pkg;
Now I don't get any lint errors in the editor to suggest the changes from the error message so I would assume main.ts should run fine. The code does work if I make the suggested changes from the error message but it would be nicer if we got the error in the editor (or when running tsc) rather than during runtime, or if it is possible for typescript to compile this to working javascript.
I've been struggling with this for years but always found one way or another which allowed typescript to target commonjs. But now when more and more packages only distribute ESM versions (eg. node-fetch and tinyhttp) I really need to find a solution to this.
Are there any typescript options or node flags so typescript can compile this to working javascript or maybe eslint rules to at least show the error in the editor? Should the code even compile if it doesn't run?