2017-05-28 69 views
0

我正尝试从grunt迁移到现有Typescript项目上的Webpack。即使我无法使用正确的import语句导入依赖关系,webpack构建也会成功。Typescript Webpack模块解析仅在运行时失败

tsconfig.json

{ 
    "compilerOptions": { 
     "target": "ES5", 
     "sourceMap": true, 
     "module": "commonjs", 
     "allowJs": true 
    }, 
    "files": [ 
     "client/Index.ts" 
    ], 
    "exclude": [ 
     "node_modules" 
    ], 
    "types": [] 
} 

webpack.config.js

const path = require('path'); 

module.exports = { 
    entry: './client/Index.ts', 
    resolve: { 
     extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'] 
    }, 
    module: { 
     loaders: [ 
      { 
       test: /\.ts$/, 
       loader: 'ts-loader', 
       exclude: /node_modules/ 
      } 
     ] 
    }, 
    output: { 
     filename: 'bundle.js', 
     path: path.resolve(__dirname, 'public', 'js') 
    } 
} 

client/Index.ts

//import * as $ from "jquery"; 
$(() => { 
    $(".title").html("Jquery works"); 
}); 

relevant dependencies from package.json

... 
    "dependencies": { 
    "@types/jquery": "^2.0.45", 
    "jquery": "^3.2.1", 
    "ts-loader": "^2.1.0", 
    "typescript": "^2.3.3", 
    "webpack": "^2.6.1" 
} 
... 

即使将import语句注释掉了,webpack的构建也完成了 - 我猜是因为它能够隐式地查找jQuery类型文件。在运行时,我收到错误Uncaught ReferenceError: $ is not defined。这是有道理的,因为webpack不捆绑./~/jquery/dist/jquery.js。如果我在Index.ts中取消注释,模块捆绑应用程序运行良好。所以我的问题是,如果我没有导入引用的模块,我将如何让Webpack在构建时失败?

谢谢!

回答

0

Typescript编译器通过查看node_modules来使用它的隐式类型解析,所以它编译虽然webpack不包含实际的js库,除非使用import。可以通过设置compilerOptions.types: []来禁用此默认的Typescript行为。

发布的代码包含错误:tsconfig.json在错误的地方有"types": []。空类型阵列所属compilerOptions.types

{ 
    "compilerOptions": { 
     "target": "ES5", 
     "sourceMap": true, 
     "module": "commonjs", 
     "allowJs": true, 
     "types": [] 
    }, 
    "files": [ 
     "index.ts" 
    ], 
    "exclude": [ 
     "node_modules/*" 
    ] 
} 

有了这个tsconfig,的WebPack不能进行正常与: ERROR in ./client/Index.ts (2,1): error TS2304: Cannot find name '$'.

相关问题