首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将平原JS导入TypeScript (没有类型)

如何将平原JS导入TypeScript (没有类型)
EN

Stack Overflow用户
提问于 2016-03-08 13:56:39
回答 1查看 10K关注 0票数 13

我们有一个在Webpack中使用TypeScript和ts加载程序的项目,因为我们现在使用的大多数东西都是类型明确的定义(通过typings),但不是我们现在想要使用的类型定义:redux-auth

首先,我没有在module中定义tsconfig.json并通过

代码语言:javascript
运行
复制
import { EmailSignInForm } from "redux-auth/bootstrap-theme"

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

此外,我在本文介绍TS 1.8中读到,它现在应该支持普通的JS文件,但没有详细解释如何支持。启用了allowJs。

如何导入该模块?谢谢!

这是我们的webpack.config.js:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
{
  "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的留言:

代码语言:javascript
运行
复制
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.
EN

回答 1

Stack Overflow用户

发布于 2016-08-22 18:28:14

代码语言:javascript
运行
复制
# declarations.d.ts
declare module '*';

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

如果您有一个模块的类型,代码完成应该可以工作,编译器将假设您知道自己在做什么。我认为T装载机也应该尊重这一点。请测试并通知我。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35869323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档