我将使用Angular 1.x的javascript项目转换为WebPack和TypeScript(使用ts-loader)。我得到它主要工作,但是当ts-loader似乎是在未直接使用导出时优化我的脚本时,我遇到了麻烦。
这是一个展示问题的示例项目(npm install,webpack,然后加载index.html并观察控制台)。
https://github.com/bbottema/webpack-typescript
显示来自ClassA的日志记录,但angular报告缺少ClassB(提供程序)。如果你查看bundle.js,你会发现ClassB完全丢失了。不同之处在于ClassA在导入后直接开始使用,而ClassB仅由类型引用进行编译。
这是一个错误,还是有办法强制包含ClassB?或者我错了吗? Angular 2可能会解决这个问题,但现在这个步骤太大了。
上述项目的相关脚本:
的package.json
{
"devDependencies": {
"typescript": "^1.7.5",
"ts-loader": "^0.8.1"
},
"dependencies": {
"angular": "1.4.9"
}
}
webpack.config.js
var path = require('path');
module.exports = {
entry: {
app: './src/entry.ts'
},
output: {
filename: './dist/bundle.js'
},
resolve: {
root: [
path.resolve('./src/my_modules'),
path.resolve('node_modules')
],
extensions: ['', '.ts', '.js']
},
module: {
loaders: [{
test: /\.tsx?$/,
loader: 'ts-loader'
}]
}
};
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs"
},
"exclude": [
"node_modules"
]
}
的index.html
<!doctype html>
<html ng-app="myApp">
<body>
<script src="dist/bundle.js"></script>
</body>
</html>
entry.js
declare var require: any;
'use strict';
import ClassA = require('ClassA');
import ClassB = require('ClassB');
var a:ClassA = new ClassA(); // direct use, this works
var angular = require('angular');
angular.module('myApp', []).
// this compiles as it should, but in runtime the provider will not be packaged and angular will throw an error
run(function(myProvider: ClassB) {
}
);
ClassA.ts
// this line will be logged just fine
console.log('ClassA.ts: if you see this, then ClassA.ts was packaged properly');
class ClassA {
}
export = ClassA;
ClassB.ts
declare var require: any;
// this line is never logged
console.log('ClassB.ts: if you see this, then ClassB.ts was packaged properly');
class ClassB {
}
var angular = require(angular);
angular.module('myApp').service(new ClassB());
export = ClassB;
答案 0 :(得分:1)
Turns out you have to signal WebPack通过在没有require
声明的情况下添加额外import
次来明确包含模块。
我还没准备好通过添加重复的导入来破坏我的.ts文件,所以我使用preprocessor loader为它做了一个通用的解决方案:
{
"line": false,
"file": true,
"callbacks": {
"fileName": "all",
"scope": "line",
"callback": "(function fixTs(line, fileName, lineNumber) { return line.replace(/^(import.*(require\\(.*?\\)))/g, '$2;$1'); })"
}]
}
作为概念证明,此正则表达式版本非常有限,它仅支持以下格式:
import ClassA = require('ClassA');
// becomes
require('ClassA');import ClassA = require('ClassA');
但它对我有用。同样,我正在添加require shim:
{
"fileName": "all",
"scope": "source",
"callback": "(function fixTs(source, fileName) { return 'declare var require: any;' + source; })"
}
我使用此解决方案制作了sample project。