網站搜尋

node.js - 如何在 Node 中強制 TypeScript 在導入 ES6 模組時不需要 .js 擴展名?


我已經設置了一個使用 TypeScript 的 Node API,運作正常。

然而,要導入一個 ES6 擴展,我必須包含 .js,即使該文件是 .ts。

在導入行中使用 .ts 擴展名或省略擴展名會導致錯誤:

CustomError: Cannot find module 'C:\.....\src\models'
server.ts
import express from 'express';
import dotenv from 'dotenv';
import { user } from './models.js';

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3049;

app.get('/', (req: express.Request, res: express.Response) => {
    res.send(user);
});

app.listen(PORT, () => {
    console.log(`listening on port http://localhost:${PORT}`);
});
models.ts
import { IUser } from './interfaces.js';

export const user: IUser = {
    firstName: "Hendrick",
    lastName: "Denzmann",
    accessGroups: ['loggedInUsers', 'members']
};

我在 package.json 中使用這個命令啟動我的應用程式:

"scripts": {
    "dev": "nodemon"
},

這裡是我的配置文件:

nodemon.json
{
    "watch": [""],
    "ext": "ts",
    "exec": "./node_modules/.bin/ts-node-esm src/server.ts"
}
tsconfig.json
{
    "compilerOptions": {
        "target": "es6",
        "allowSyntheticDefaultImports": true,
        "moduleResolution": "node",
        "module": "esnext",
        "outDir": "build"
    }
}

我需要改變什麼才能讓我在不加副檔名的情況下匯入我的 ES6 模組,例如這樣:import { user } from './models';?

答案#1

你需要告訴 Node 二進位檔停止要求擴展。目前這是透過一個實驗性標誌完成的,--experimental-specifier-resolution=node。然後你可以改用 ts-node 作為載入器。

基本上,只需將你的 nodemon.json 中的 exec 部分改成這個即可:

{
  "watch": [""],
  "ext": "ts",
  "exec": "node --experimental-specifier-resolution=node --loader ts-node/esm src/server.ts"
}