【问题标题】:How to use paths in tsconfig for a single module?如何将 tsconfig 中的路径用于单个模块?
【发布时间】:2019-05-02 09:17:25
【问题描述】:

这个问题是How to use paths in tsconfig.json? 的后续问题,除了我想针对单个模块进行。

我有一个模块:

  • src/functions/foo.ts中实现
  • 它的内容是:

    export default interface Bar {
    }
    
  • 它是由另一个模块在其他地方使用非相对路径导入的:

    import * as Foo from "foo"
    

编译器没有找到:

error TS2307: Cannot find module 'foo'

这个 tsconfig 不能解决这个问题...

{ "compilerOptions": { "noEmit": true, "strict": true, "module": "commonjs", "target": "es2017", "noImplicitAny": true, "moduleResolution": "node", "sourceMap": true, "outDir": "build", "baseUrl": ".", "paths": { "foo": ["src/functions/*"], "*": [ "node_modules/*" ] } }, "include": [ "./src/**/*", "./typings/**/*", "./test/**/*", "./test-integration/**/*" ] }

...但确实如此:

"paths": { "*": [ "node_modules/*", "src/functions/*" ] }


为什么paths 的第一个版本不起作用 --- 我做错了什么,我能做些什么来确保 "src/functions/*" 仅在导入 foo 时使用(而不是在导入 * 时使用)?

(我在带有 Node.js 的 Windows 上使用 tsc 版本 3.1.6)。

【问题讨论】:

    标签: typescript tsconfig


    【解决方案1】:

    您正在将单词 foo 分配给目录 src/functions/* 的内容。

    但是foo之类的只能用来指定单个文件(模块)的准确位置,没有通配符,所以,像这样:

    "paths": {
        "foo": ["src/functions/foo"],
        "*": [
            "node_modules/*"
        ]
    }
    

    您可能正在寻找的是

    "paths": {
        "foo/*": ["src/functions/*"],
        "*": [
            "node_modules/*"
        ]
    }
    

    foo/* 而不是foo

    【讨论】:

    • 谢谢,这是我要找的第一个。如果我想通过使用import * as BAR from "@foo/bar"src/functions/bar.ts 导入一些东西,我认为第二个会被使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多