【问题标题】:Typescript import returns "Cannot find module"打字稿导入返回“找不到模块”
【发布时间】:2020-07-29 16:34:54
【问题描述】:

我正在尝试将模块导入为import Something from "@module",但它返回了

找不到模块“@config”

“@module”是“./src/utils/module”的别名

“app.ts”

import 'module-alias/register';

import Something from '@module';

"/utils/module.ts"

export enum Something {
    CONSTANT = 'constant'
}

“package.json”

{
  "name": "crawler",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "dev": "nodemon ./src/app.ts",
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^13.11.1",
    "nodemon": "^2.0.3",
    "ts-node": "^8.8.2",
    "typescript": "^3.8.3"
  },
  "dependencies": {
    "module-alias": "^2.2.2"
  },
  "_moduleAliases": {
    "@module": "./src/utils/module"
  }
}

“tsconfig.json”

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "lib": [
      "es6"
    ],
    "outDir": "dist",
    "noEmitOnError": true,
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "paths": {
    "@module": [
      "./src/utils/module"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

为什么import "@module"const Something = require('@module') 工作正常,而import Something from "@module" 返回找不到模块错误?

这是项目结构:

- crawler
|-- src
    -- app.ts
    |-- utils
        -- module.ts

【问题讨论】:

  • "paths" 应该在 "compilerOptions" 部分,而不是在根目录中
  • 难以置信...花了 2 个小时在这件事上,但没有检查 compilerOptions 部分!您应该发表您的评论作为解决方案。
  • 是的,很遗憾,tsconfig 没有被编译器检查冗余/额外属性

标签: javascript node.js typescript import


【解决方案1】:

"paths" 应该在 "compilerOptions" 部分,而不是在 tsconfig.json 的根目录中

更多关于路径映射的信息here

tsconfig.jsonhere概述

【讨论】:

    【解决方案2】:

    请注意,在通过这种方式导入 moment 进行开发时,导入看起来不错,但是在进行 prod 编译时可能会出现 AOT 错误,例如“无法使用引用”或类似的东西。为了不详细说明,这与一些 CommonJS 模块有关(据我所知)。 Moment 很受欢迎,所以出现的次数似乎不少。

    要解决这个问题(我在几周前遇到过),请将“moment”设置为 const:

    import * as moment from 'moment':
    
    (later where you declare consts)
    
    const _moment = moment;
    

    然后您在代码中使用 _moment。

    【讨论】:

      【解决方案3】:

      我有一个类似的“时刻”问题,我已经导入如下,它确实有效。

      import * as moment from 'moment';
      

      【讨论】:

        猜你喜欢
        • 2020-03-02
        • 2021-01-07
        • 2013-12-30
        • 1970-01-01
        • 1970-01-01
        • 2021-05-15
        • 2018-06-27
        相关资源
        最近更新 更多