Import js file with TypeScript 2.0

后端 未结 2 715
栀梦
栀梦 2021-02-12 21:57

Abstract

I\'m trying to import \".js\" file from an external location (i.e. node_modules) I\'m trying to do this using commonjs module pattern, howeve

相关标签:
2条回答
  • 2021-02-12 22:07

    being able to define it's ".d.ts" declarations while having both files located in different locations.

    import follows the same module resolution process when given a .js or .d.ts file with relative files.

    0 讨论(0)
  • 2021-02-12 22:26

    Note: The official recommendation for proving your type definitions takes a slightly different approach than what is presented below. I believe the approach below is slightly better as the *.d.ts file is practically identical to the final product.

    During typechecking (build time) TypeScript works with *.ts files and (mostly) ignores *.js files. Let me offer an example that motivates what (I believe) you are proposing. Suppose there exists a perfectly good JavaScript library that sadly has no typings (e.g. N3). Which has been installed via npm, thus:

    npm install n3 --save
    

    This, as is typical, is added to ./node_modules/n3/... and project.json. As mentioned the typings does not exist and needs to be added manually. I create an ./@types/n3.d.ts file for this purpose. For our purposes it is not particularly important what the definitions actually are but something like the following is a good start:

    declare namespace N3 {
    }
    
    declare module "n3" {
        export = N3;
    }
    

    Now to your question. Update the 'tsconfig.json':

    ...
    "compilerOptions": {
        "typeRoots": [
          "node_modules/@types",
          "@types"
        ],
    ...
    "paths": {
      "*": [
        ...
        "./@types/*"
      ]
    

    It will still be necessary to deal with the run-time resolution for locating the corresponding *.js files but that is a different question than the one you asked.

    For reference you may find What is new in TypeScript and this discussion thread useful.

    This approach works fine when working with global variables but not so much with modules.

    Update the 'tsconfig.json':

    ...
    "paths": {
      "*": [
        ...
        "./@types/*"
      ],
      "foo": [ "./@types/foo.d.ts" ]
      },
     ...
    
    0 讨论(0)
提交回复
热议问题