提问者:小点点

如何用TypeScript1.8包含非类型化节点模块?


TypeScript1.8现在支持非类型化的JS文件。要启用此特性,只需添加编译器标志--allowJs或将“allowJs”:true添加到tsconfig.json中的compilerOptions中

通过https://blogs.msdn.microsoft.com/typescript/2016/01/28/uncasting-typescript-1-8-beta/

我正在尝试导入react-tap-event-plugin,它没有一个类型文件。

import * as injectTapEventPlugin from 'injectTapEventPlugin'; 

表示未找到模块。所以我试着:

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

这表示模块解析为非模块实体,不能使用此构造导入。然后我试着:

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

由于./scripts/index.tsx中的错误而崩溃:模块生成失败:TypeError:无法读取node_modules/typescript/lib/typescript中未定义的属性“kind”。js:39567

我的tsconfig:

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

我将webpack与TS-Loader一起使用:

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

共1个答案

匿名用户

新的--allowJS特性并不意味着将为您生成类型,因此您不能

import {SomeModule} from 'something';

其中“something”是一个普通的JS文件--您必须使用普通的JS语法导入它,例如。

var someModule = require('something');

如果没有用于导入的.d.ts文件,则无法使用任何类型注释,例如。

let x: someModule

将无效。如果您想要为导入提供类型注释、智能感知和任何其他TypeScript功能,则必须为其提供一个.d.ts文件,或者为所需的位创建自己的接口。

阅读文档可以发现,这个特性主要是为将.js转换为.ts的用户提供的,这样他们就可以递增地重写他们的.js文件。此外,它还用于将外部文件与自己的代码捆绑在一起,从而节省了使用webpack或Browserify等工具捆绑/连接文件的时间。