如何在Typescript 1.8中包含无类型的节点模块?

Fro*_*yon 12 javascript node-modules typescript ecmascript-6 ts-loader

Typescript 1.8现在支持无类型的JS文件.要启用此功能,只需添加编译器标志--allowJs或将"allowJs":true添加到tsconfig.json中的compilerOptions

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

我正在尝试导入没有打字文件的react-tap-event-plugin.

import * as injectTapEventPlugin from 'injectTapEventPlugin'; 
Run Code Online (Sandbox Code Playgroud)

说找不到模块.所以我试过:

import * as injectTapEventPlugin from '../node_modules/react-tap-event-plugin/src/injectTapEventPlugin.js';
Run Code Online (Sandbox Code Playgroud)

这表示模块解析为非模块实体,无法使用此结构导入.然后我尝试了:

import injectTapEventPlugin = require('../node_modules/react-tap-event-plugin/src/injectTapEventPlugin.js');
Run Code Online (Sandbox Code Playgroud)

它与崩溃ERROR in ./scripts/index.tsx Module build failed: TypeError: Cannot read property 'kind' of undefinednode_modules/typescript/lib/typescript.js:39567

我的tsconfig:

{
  "compilerOptions": {
  "target": "ES5",
  "removeComments": true,
  "jsx": "react",
  "module": "commonjs",
  "sourceMap": true,
  "allowJs": true
  },
  "exclude": [
    "node_modules"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我正在使用带有ts-loader的webpack:

 {
   test: /\.tsx?$/,
   exclude: ['node_modules', 'tests'],
   loader: 'ts-loader'
 }
Run Code Online (Sandbox Code Playgroud)

小智 5

新的--allowJs功能并不意味着将为您生成打字,因此您无法做到

import {SomeModule} from 'something';
Run Code Online (Sandbox Code Playgroud)

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

var someModule = require('something');
Run Code Online (Sandbox Code Playgroud)

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

let x: someModule
Run Code Online (Sandbox Code Playgroud)

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

阅读文档,看来这个功能主要是为了从.js转换为.ts的人,以便他们可以逐步重写他们的.js文件.同样,它用于将您的外部代码与您自己的代码捆绑在一起,并且使您可以使用webpack或browserify等工具捆绑/连接文件.

  • 在我看来``someModule}来自'something';`是*简单的JS语法*自ES2015以来......所以如果我在ES2015项目中使用那个import语句然后想要迁移到TS,那么我会有将所有`import`语句更改为`require`语句(对于没有打字的库,以及我尚未迁移的代码)?...这将是一个非常痛苦......如果是这样的话,那么我会声称TS不是JavaScript的超集*! (3认同)