简体   繁体   中英

how to use @types/module in combination with with npm module that types are written for?

This is just example of some module that I have in my project.

There is a https://github.com/mapbox/polylabel TypeScript type definitions for npm module polylabel. Now when i do install npm install --save @types/polylabel i got types but when i install npm install --save polylabel I got npm module it self.

So my question is how to import polylabel but for that module to use TypeScript type definitions from that @types/polylabel ? Example:

import polylabel from "polylabel";

export default class SomeClass extends Base {

   console.log(polylabel(coordinates, 1.0))
}

Now this will not work since typescript will try to import function that is definition without functionality from module it self.

Should I include module it self in webpack it self or there is another way to do that? Webpack part:

new webpack.ProvidePlugin({
  polylabel: 'polylabel'
}),

I hope that question is clear on what i am trying/need to resolve.

As long as you have your tsconfig.json setup to reference the @types directory, it will always use types if they are available. Sometimes npm packages will come packaged with type definitions but in a lot of cases, they don't. This is when you need to run the npn install @types/<module> --save-dev

Example tsconfig.json :

{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types" // <-- This guy
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  },
  "exclude": [
    "node_modules",
    "e2e"
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM