[英]How to use TypeScript with Sequelize when targeting ESM
我有以下項目:
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");
}
當我運行它時( npm run build && npm start
)我收到以下錯誤:
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;
現在我在編輯器中沒有收到任何提示錯誤消息更改的 lint 錯誤,所以我假設main.ts
應該運行良好。 如果我根據錯誤消息進行建議的更改,代碼確實有效,但如果我們在編輯器中(或運行tsc
時)而不是在運行時出現錯誤,或者如果 typescript 可以將其編譯為正常工作,則代碼會更好javascript。
多年來,我一直在為此苦苦掙扎,但總能找到一種或另一種方法,使 typescript 能夠以 commonjs 為目標。 但是現在越來越多的包只分發 ESM 版本(例如 node-fetch 和 tinyhttp),我真的需要找到一個解決方案。
是否有任何 typescript 選項或節點標志,以便 typescript 可以將其編譯為工作 javascript 或者可能是 eslint 規則至少在編輯器中顯示錯誤? 如果代碼不運行,它是否應該編譯?
我不知道你是否還有這個問題,但我有。
我設法通過更新我所有的模塊來解決它。 就我而言,這也意味着將 sequelize 更新到版本 6.23.2。
所以在我的package.json
中,我現在有這個:
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"compile": "tsc",
"start": "npm run compile && nodemon ./build/index.js",
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"nodemon": "^2.0.20",
"pg": "^8.8.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.23.2",
"sqlite3": "^5.1.1",
"typescript": "^4.8.4"
}
}
在我的tsconfig.json
{
"buildOptions": {
},
"compilerOptions": {
"outDir": "build",
"target": "ES2017",
"module": "ESNext",
"moduleResolution": "node",
},
}
而且我沒有其他關於 sequelize 的導入錯誤。
順便說一下,如果你想遵循這個提示, 這里是你如何更新你的節點模塊——或者我是如何做到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.