如何为Angular2测试配置webpack?
我已经设置了基于webpack的配置来测试Angular2 npm包.
无论如何,我不断收到如下错误:
Error: This test module uses the component PaginationComponent which is using a “templateUrl”,but they were never compiled. Please call “TestBed.compileComponents” before your test. in karma-test-shim.js (line 9952)
在我看来,我做的一切都是正确的,它应该工作.应该通过webpack加载html和scss文件.
如果你想检查完整的配置,我已将它上传到GitHub.你可以找到webpack.test.js,karma.conf.js,package.json以及项目源.它很小 – 一个组件项目.
这是我的webpack配置:
var path = require('path'); var _root = path.resolve(__dirname,'..'); module.exports = { devtool: 'inline-source-map',resolve: { extensions: ['','.ts','.js','.json','.css','.scss','.html'] },module: { loaders: [ { test: /\.ts$/,loaders: ['awesome-typescript-loader','angular2-template-loader'] },{ test: /\.html$/,loader: 'html' },{ test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,loader: 'null' },{ test: /\.json$/,loader: 'json' },{ test: /\.css$/,exclude: root('src'),include: root('src'),loader: 'raw' },{ test: /\.scss$/,loader: 'raw!postcss!sass' } ] } }; function root(args) { args = Array.prototype.slice.call(arguments,0); return path.join.apply(path,[_root].concat(args)); }
解决方法
问题出在TypeScript配置上.
tsconfig.json:
{ "compilerOptions": { "target": "es5","module": "commonjs","moduleResolution": "node","sourceMap": true,"emitDecoratorMetadata": true,"experimentalDecorators": true,"removeComments": false,"noImplicitAny": true,"suppressImplicitAnyIndexErrors": true,"declaration": true,"outDir": "./lib","noEmitHelpers": false,"isolatedModules": false },"compileOnSave": false,"buildOnSave": false,"exclude": [ "components.d.ts","typings/browser.d.ts","typings/browser","node_modules","examples" ] }
选项“声明”:true会触发生成类型* .d.ts文件,这使得IDE Intellisense能够在测试期间调用webpack来抛出错误.
我通过在运行构建时测试和取消注释时注释掉这一行来解决这个问题.