2016-03-08 21 views
9

我们有一个在Webpack中使用带有ts-loader的TypeScript的项目,因为我们现在使用的大多数东西都有绝对类型中的类型定义(通过typings),但不是我们现在想用的那个:redux-auth如何将纯JS导入TypeScript(无类型)

起初,我不得不通过

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

导致Cannot find module在tsconfig.json和进口它没有定义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的符号)

UPDATE :

好吧,那么如果我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. 
+0

这就是从我收集 – Angad

+0

预期的方式在这里,我的回答可以帮助:http://stackoverflow.com/questions/37656592/define-global-variable-with-webpack/40416826#40416826 – prograhammer

回答

2
# declarations.d.ts 
declare module '*'; 

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

如果您有类型为一个模块的代码应该完成的工作和编译器将假定你知道你在做什么。我认为ts loader也应该尊重这一点。请测试并让我知道。

+0

我错过了一个事实,即“声明”声明最初必须在单独的文件中。添加一个'declarations.d.ts'文件,其中包含'declare module'libToInclude';'为我工作。 –

+0

所以你可以标记为已解决? – qballer

+0

Idk你的意思。我没有问这个问题。我只是在评论,希望阻止其他人花费一段时间试图弄清楚这一点。我想我通过Google搜索结果时太快地读完了这个答案... –

相关问题