How to use paths in tsconfig for a single module?

佐手、 提交于 2020-01-06 07:27:12

问题


This question is a follow-on from How to use paths in tsconfig.json? except I want to do it for a single module.

I have a module:

  • It's implemented in src/functions/foo.ts
  • Its contents are:

    export default interface Bar {
    }
    
  • It's imported by another module elsewhere using a non-relative path:

    import * as Foo from "foo"
    

The compiler doesn't find it:

error TS2307: Cannot find module 'foo'

This tsconfig doesn't fix that problem ...

{ "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/**/*" ] }

... but this does:

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


Why didn't the first version of paths work --- what was I doing wrong, what can I do to ensure that "src/functions/*" is used only when importing foo (and not when importing *)?

(I'm using tsc version 3.1.6 on Windows with Node.js).


回答1:


You are assigning a word foo to the content of a directory src/functions/*.

But foo like that can only be used to specify the exact location of a single file (module), without a wildcard, so, like this:

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

What you are probably looking for is

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

(foo/* instead of foo)



来源:https://stackoverflow.com/questions/53553772/how-to-use-paths-in-tsconfig-for-a-single-module

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