简体   繁体   中英

Load an npm module inside a typescript project

I'm working in a project and I need to load a module that it is not in typescript. In a folder called typings I have all the typescript modules while in the folder node_modules I have the javascript version. The problem is that when I try to import that module it is not found. how can I solve this issue?

In typings you don't have an implementation of the module in typescript but the type definitions of a javascript module (which might be in node_modules ). See definitelytyped.org/ for more information.

You can install the type definitions of a mudule with

$ tsd query PACKAGE_NAME -a install --save

With this command your tsd.json file will be updated and when you execute tsd reinstall , that package will be installed again. That's also nice if other people are working on the project. They can install all type definitions with tsd reinstall (as long as tsd.json is in your repository).

In you .ts file you import the javascript module with

import MODULE = require ('MODULE');

and load the type definitions with

/// <reference path="../../../typings/MODULE/MODULE.d.ts" />

Of course you have to adapt the path and names. If you don't have type definitions, you can load your javascript module with

declare var require: any;
var MODULE = require('MODULE');

tsd install node

Followed by

var theJsModule = require('the-js-module');

Compile with --module commonjs

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