Typescript import returns “Cannot find module”

痴心易碎 提交于 2021-02-17 06:21:16

问题


I'm trying to import a module as import Something from "@module", but it returns

Cannot find module '@config'

"@module" is an alias to "./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"
  ]
}

Why does import "@module" and const Something = require('@module') work fine, while import Something from "@module" returns the cannot find module error?

This is the project structure:

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

回答1:


"paths" should be in "compilerOptions" section, not in root of tsconfig.json

More info on path mapping here

Overview of tsconfig.json here




回答2:


I had a similar issue with "moment" I have import like below and it does work.

import * as moment from 'moment';



回答3:


Note that the import will seem fine while developing by importing moment this way, but you may get an AOT error when doing a prod compile, something like, "can not use reference" or some such like that. To not elaborate over much, this has to do (as I understand it) with some CommonJS modules. Moment is very popular, so it seems to come up quite a bit.

To get around that one (which I ran into a couple of weeks ago), set "moment" to a const:

import * as moment from 'moment':

(later where you declare consts)

const _moment = moment;

And then you use _moment in your code.



来源:https://stackoverflow.com/questions/61250213/typescript-import-returns-cannot-find-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!