【问题标题】:Typescript: let module resolution (paths/base), dynamic imports and resolveJsonModule work togetherTypescript:让模块解析(路径/基础)、动态导入和 resolveJsonModule 协同工作
【发布时间】:2021-01-21 00:24:05
【问题描述】:

问题

我在尝试使用带有路径、json 文件导入和动态导入的 typescripts 模块解析时遇到了一些问题。这就是我所做的:

  • 首先:我介绍了"resolveJsonModule": true 能够导入.json 文件
  • 第二:我引入(使用)动态导入(运行良好)
  • 第三:我引入了模块(路径),如下例所示(我的问题来了)

我不确定,如果我在这里混淆了一些东西。但是,如果能够同时使用以下三个,我们将不胜感激:

  • 1 个动态导入
  • 2个导入json文件
  • 3使用typescript模块解析

信息:

  • 我的节点版本:v11.14.0
  • 我可以使用最新的节点版本,所以这里没有限制

代码:

// 1. dynamic import
const subfolder = 'example'
let { ex } = await import(`./../../some/path/${subfolder}`)
// 2. json file import
import config from './../../config.json'
// 3. module resolution
// some/path/file_a.ts
import { example_function } from '@utils/ex'
...
const result = await example_function()

// src/utils/ex/index.ts
export async function example_function() {}

错误:

上面的代码正在通过编译器运行并且构建没有错误。 但是当我尝试启动编译后的代码时,我会收到这样的错误:

➤ node lib/index.js
internal/modules/cjs/loader.js:670
    throw err;
    ^

Error: Cannot find module '@utils/ex'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:668:15)
    at Function.Module._load (internal/modules/cjs/loader.js:591:27)
    at Module.require (internal/modules/cjs/loader.js:723:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (/home/mod/cod/wo/thingylabs/calpobot/cb1/lib/utils/pipeline/pipelineRunChatops.js:52:12)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Module.require (internal/modules/cjs/loader.js:723:19)

尝试解决问题

  • 我尝试更改以尝试使用模块和 moduleResolution 但没有成功

我的完整 tsconfig.json

{
  "compilerOptions": {
    "allowJs": false,
    "lib": ["es2015", "es2017"],
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es5",
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": false,
    "pretty": true,
    "strict": true,
    "sourceMap": true,
    "outDir": "./lib",
    "skipLibCheck": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "declaration": true,
    "resolveJsonModule": true,
    "baseUrl": "./src",
    "paths": {
      "@utils/fs": ["utils/fs"],
      "@pipelines/*": ["pipelines/*"],
      "@jobs/*": ["jobs/*"],
    }
  },
  "include": [
    "src/**/*"
  ],
  "compileOnSave": false
}

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    您在此处讨论的问题:https://github.com/microsoft/TypeScript/issues/24715 作为一种解决方法,您可以替换

    import config from './../../config.json'
    

    const config = require('./../../config.json')
    

    【讨论】: