有没有人知道如何输出编译的typescript作为字符串,可以使用Extract-Text-Webpack-Plugin提取?
目前我使用“ts-loader”将TypeScript文件转换为JavaScript文件。 但是,结果并不像预期的那样,因为输出JavaScript与将由NodeJ执行的Js集成。
预期的结果是将TypeScript内容编译成JavaScript字符串,就像Css加载器一样,所以我可以使用Extract-Text-WebPack-Plugin将已编译的Javascript内容呈现到输出文件中(捆绑的js文件将会用作浏览器端javascript库)。
不确定哪个webpack插件/加载器能够解决这个问题?
webpack.config.js
var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var exCss = new ExtractTextPlugin('[name].bundle.css');
var exScss = new ExtractTextPlugin('[name].bundle.css');
module.exports = {
entry: {
entry:"./src/entry.js"
},
devtool: "source-map",
output: {
path: __dirname + "/bundle",
publicPath: "/assets/",
filename: "[name].bundle.js"
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.jsx']
},
module: {
loaders: [
{ test:/\.ts$/, loader: "ts-loader" },
{ test: /\.css$/, loader: exCss.extract(["css"]) }
]
},
plugins: [exScss, exCss]
};
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings"
]
}
TypeScript文件:test.ts
class FirstType{
firstProp: "ok";
}
let obj = new FirstType();
console.log(obj.firstProp);
预期结果:test.bundle.js
"use strict";
var FirstType = (function () {
function FirstType() {
this.firstProp = "ok";
}
return FirstType;
}());
var obj = new FirstType();
console.log(obj.firstProp);
不需要的实际结果:test.bundle.js
/******/ (function(modules) { // webpackBootstrap
...
function(module, exports) {
"use strict";
var FirstType = (function () {
function FirstType() {
this.firstProp = "ok";
}
return FirstType;
}());
var obj = new FirstType();
console.log(obj.firstProp);
}
]);
答案 0 :(得分:1)
您可以使用自定义加载程序实现这一目标。
module.exports = function(source){
var src = source;
src = src.replace(/\\/ig, "\\\\");
src = src.replace(/\'/ig, "\\'");
src = src.replace(/\"/ig, "\\\"");
src = src.replace(/\r/ig, "\\r");
src = src.replace(/\n/ig, "\\n");
return 'var content = "'+src+'";module.exports = content;';
};