Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
 }
like image 966
Frozen Crayon Avatar asked Feb 04 '16 12:02

Frozen Crayon


1 Answers

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, e.g.

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, e.g.

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.

like image 167
clappski Avatar answered Oct 18 '22 04:10

clappski