无法导入带有扩展名的TypeScript文件

huangapple go评论67阅读模式
英文:

Cannot import typescript files with the extension

问题

以下是你提供的代码部分的中文翻译:

我在./models文件夹中的多个.ts文件中声明了实体,我尝试导入并在我的应用程序中使用它们,如下所示:

import { DataSource } from "typeorm";
import { User } from "../models/User";
import { Company } from "../models/Company";
import { CompanyUser } from "../models/CompanyUser";

const initDB = () => {
  const AppDataSource = new DataSource({
    type: "postgres",
    host: process.env.BACKEND_URL,
    port: process.env.DB_PORT as unknown as number,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    entities: [User, Company, CompanyUser],
    synchronize: true,
    logging: true,
  });

  AppDataSource.initialize()
    .then(() => {
      console.log("已连接到数据库");
    })
    .catch((error) => {
      console.log("连接数据库失败:", error);
    });
};

export { initDB };

在编译时,我收到以下错误:

CustomError: 无法找到模块 'C:\Users\Yu\Desktop\Projects\keytest\keytest-backend\models\User',从 C:\Users\Yu\Desktop\Projects\keytest\keytest-backend\utils\database.ts 导入

我的tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ES6",
    "outDir": "./dist",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false
  },
  "ts-node": {
    "esm": true
  }
}
英文:

I have entities declared in multiple .ts files in ./models, which I'm trying to import and use in my application, like this:

import { DataSource } from "typeorm";
import { User } from "../models/User";
import { Company } from "../models/Company";
import { CompanyUser } from "../models/CompanyUser";

const initDB = () => {
  const AppDataSource = new DataSource({
    type: "postgres",
    host: process.env.BACKEND_URL,
    port: process.env.DB_PORT as unknown as number,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    entities: [User, Company, CompanyUser],
    synchronize: true,
    logging: true,
  });

  AppDataSource.initialize()
    .then(() => {
      console.log("Connected to the DB");
    })
    .catch((error) => {
      console.log("Failed to connect to the DB: ", error);
    });
};

export { initDB };

On compiling, this is the error I get:

CustomError: Cannot find module 'C:\Users\Yu\Desktop\Projects\keytest\keytest-backend\models\User' imported from C:\Users\Yu\Desktop\Projects\keytest\keytest-backend\utils\database.ts

My tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "ES6",                                  /* Specify what module code is generated. */
    "outDir": "./dist",                               /* Specify an output folder for all emitted files. */
    "moduleResolution": "node",
    "esModuleInterop": true,                          /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,         /* Ensure that casing is correct in imports. */
    "strict": true,                                   /* Enable all strict type-checking options. */
    "skipLibCheck": true,                             /* Skip type checking all .d.ts files. */
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
  },
  "ts-node": {
    "esm": true
  }
}

答案1

得分: 2

由于您正在使用一个模块,您需要使用.js扩展名。
有关更多信息,请参阅https://www.typescriptlang.org/docs/handbook/esm-node.html#type-in-packagejson-and-new-extensions

因此,您需要更改:

import { User } from "../models/User.js";
import { Company } from "../models/Company.js";
import { CompanyUser } from "../models/CompanyUser.js";

并从编译后的JavaScript文件中导入。

英文:

Since you are using a module, you need to use the .js extension.
For more info, see https://www.typescriptlang.org/docs/handbook/esm-node.html#type-in-packagejson-and-new-extensions

So you need to change:

import { User } from "../models/User.js";
import { Company } from "../models/Company.js";
import { CompanyUser } from "../models/CompanyUser.js";

and import from the compiled javascript files

答案2

得分: 2

Using your settings with TypeScript 5.0.4, I was able to run tsc successfully, but I had the same error running npx ts-node utils/database.ts.

If your error was with compiling, perhaps it is because you are using an older version of TypeScript?

If the error is with ts-node, it is because you've set ts-node to use esm and thus is having trouble with the mapping of imports. To resolve this without specifying the extension in your .ts import, you can set "experimentalSpecifierResolution": "node" like so:

tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ES6",
    "outDir": "./dist",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  }
}

For more info, check out ts-node's documentation.

Of course, because you'd be compiling to JS with the same issue, you'd need to run your JS code with node --experimental-specifier-resolution=node /path/to/file.js. More info on that in node's documentation.

It's either that, or include the extension in the import like in the answer @Alexxino provided.

Cheers!

英文:

Using your settings with TypeScript 5.0.4, I was able to run tsc successfully, but I had the same error running npx ts-node utils/database.ts.

If your error was with compiling, perhaps it is because you are using an older version of TypeScript?

If the error is with ts-node, it is because you've set ts-node to use esm and thus is having trouble with the mapping of imports. To resolve this without specifying the extension in your .ts import, you can set "experimentalSpecifierResolution": "node" like so:

tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "ES6",                                  /* Specify what module code is generated. */
    "outDir": "./dist",                               /* Specify an output folder for all emitted files. */
    "moduleResolution": "node",
    "esModuleInterop": true,                          /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,         /* Ensure that casing is correct in imports. */
    "strict": true,                                   /* Enable all strict type-checking options. */
    "skipLibCheck": true,                             /* Skip type checking all .d.ts files. */
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  }
}

For more info, check out ts-node's documentation

Of course, because you'd be compiling to JS with the same issue, you'd need to run your JS code with node --experimental-specifier-resolution=node /path/to/file.js. More info on that in node's documentation.

It's either that, or include the extension in the import like in the answer @Alexxino provided.

Cheers!

huangapple
  • 本文由 发表于 2023年5月7日 01:54:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定