简体   繁体   中英

How to include untyped node modules with Typescript 1.8?

Typescript 1.8 now supports untyped JS files. To enable this feature, just add the compiler flag --allowJs or add "allowJs": true to compilerOptions in tsconfig.json

via https://blogs.msdn.microsoft.com/typescript/2016/01/28/announcing-typescript-1-8-beta/

I'm trying to import react-tap-event-plugin which does not have a typings file.

import * as injectTapEventPlugin from 'injectTapEventPlugin'; 

says module not found. So i tried:

import * as injectTapEventPlugin from '../node_modules/react-tap-event-plugin/src/injectTapEventPlugin.js';

This says Module resolves to a non-module entity and cannot be imported using this construct. And then I tried:

import injectTapEventPlugin = require('../node_modules/react-tap-event-plugin/src/injectTapEventPlugin.js');

It's crashing with ERROR in ./scripts/index.tsx Module build failed: TypeError: Cannot read property 'kind' of undefined at node_modules/typescript/lib/typescript.js:39567

My tsconfig:

{
  "compilerOptions": {
  "target": "ES5",
  "removeComments": true,
  "jsx": "react",
  "module": "commonjs",
  "sourceMap": true,
  "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}

I'm using webpack with ts-loader:

 {
   test: /\.tsx?$/,
   exclude: ['node_modules', 'tests'],
   loader: 'ts-loader'
 }

The new --allowJs feature doesn't mean that typings will be generated for you, so you can't do

import {SomeModule} from 'something';

where 'something' is a plain JS file - you have to import it using plain JS syntax, eg

var someModule = require('something');

If you don't have a .d.ts file for the import, you won't be able to use any type annotations, eg

let x: someModule

will be invalid. If you want type annotations, intellisense, and any other TypeScript features for the import, you'll have to come up with a .d.ts file for it, or create your own interfaces for the bits you need.

Reading the documentation, it appears this feature is mainly for people converting from .js to .ts so that they can incrementally rewrite their .js files. As well, it's used to bundle your externals with your own code, and saves you having to bundle/concatenate files using a tool like webpack or browserify.

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