【问题标题】:How to import plain JS into TypeScript (without Typings)如何将纯 JS 导入 TypeScript(无打字)
【发布时间】:2016-06-22 12:19:15
【问题描述】:

我们有一个在 Webpack 中使用带有 ts-loader 的 TypeScript 的项目,对于我们现在使用的大多数东西,在肯定类型中都有类型定义(通过 typings),但不是我们现在想使用的那个:redux-auth.

起初我没有在 tsconfig.json 中定义 module 并通过

导入它
import { EmailSignInForm } from "redux-auth/bootstrap-theme"

导致Cannot find module。然后我们读到使用 CommonJS 表示法可能会有所帮助,但它没有帮助,因为 TS 不知道导入模块的成员 (Property 'EmailSignInForm' does not exist on type '{}')。使用相对路径也没有任何用处。

我还在this article about TS 1.8 中读到它现在应该支持纯 JS 文件,但没有具体解释如何。 allowJs 已启用。

如何导入该模块?谢谢!

这是我们的 webpack.config.js:

var webpack = require('webpack');
var fail = require('webpack-fail-plugin');

module.exports = {
  entry: './static/files/app/main.tsx',

  output: {
    path: './static/files/',
    filename: 'bundle.js',
    sourceMapFilename: '[file].map'
  },

  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },

  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
      },
    ]
  },

  devtool: 'source-map',

  plugins: [
    fail,
    new webpack.ProvidePlugin({
      //Promise: 'exports?global.Promise!es6-shim',
      fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch'
    })
  ]
};

还有我们的 tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "sourceMap": true,
    "allowJs": true,
    "noEmitOnError": true
  },
  "files": [
    "typings/browser.d.ts"
  ],
  "exclude": [
    "typings/main.d.ts",
    "typings/main",
    "node_modules"
  ]
}

"module": "commonjs" 是临时测试 CommonJS 符号)

更新:

好的,所以如果我 declare var require: any 并使用 require() 中的相对路径,我可以导入它,尽管我怀疑这是预期的方式。有趣的是,现在我从 Webpack 收到了这条消息:

WARNING in ./~/encoding/lib/iconv-loader.js
Critical dependencies:
9:12-34 the request of a dependency is an expression
 @ ./~/encoding/lib/iconv-loader.js 9:12-34

ERROR in ./~/iconv-lite/encodings/tables/gb18030-ranges.json
Module parse failed: ./node_modules/iconv-lite/encodings/tables/gb18030-ranges.json Line 1: Unexpected token :
You may need an appropriate loader to handle this file type.

【问题讨论】:

标签: typescript


【解决方案1】:
# declarations.d.ts
declare module '*';

# someFile.ts
import * as $ from 'jquery';
import * as _ from 'lodash';

如果你有一个模块的类型,代码完成应该可以工作,编译器会假设你知道你在做什么。我认为 ts loader 也应该尊重这一点。请测试并告诉我。

【讨论】:

  • 我错过了 declare 语句最初必须位于单独文件中的事实。添加包含declare module 'libToInclude';declarations.d.ts 文件对我有用。
  • 我知道你的意思。我没有问这个问题。我只是发表评论,希望能防止其他人花一段时间试图弄清楚这一点。当我浏览 Google 搜索结果时,我想我阅读这个答案的速度太快了......
猜你喜欢
  • 2020-11-27
  • 2017-02-04
  • 2019-06-16
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2017-12-10
相关资源
最近更新 更多