我正在尝试进行测试,以了解webpack
如何编译打字稿,以便我可以从javascript转换代码。
当我使用webpack
和awesome-typescript-loader
将我的打字稿转换为javascript时,我的TEST类被导出但是为了调用构造函数我需要调用TEST.TEST,正如你在我的html测试中看到的那样文件。但这不是我所期待的。我希望能够通过var T = new TEST(); not var T = new TEST.TEST();
直接调用构造函数。
我有以下文件/代码:
的src / test.ts
export class TEST {
thing: string;
constructor(thing: string) {
this.thing = thing;
}
print_thing() {
console.log(this.thing);
}
}
的src /的test.html
<html>
<head>
<title>TEST</title>
</head>
<script src="test.js"></script>
<script>var t = new TEST.TEST("thing"); t.print_thing();</script>
<body></body>
</html>
的package.json
{
"name": "TEST",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"awesome-typescript-loader": "^4.0.1",
"del": "^3.0.0",
"gulp": "^3.9.1",
"typescript": "^2.7.2",
"webpack": "^4.2.0",
"webpack-stream": "^4.0.3"
}
}
tsconfig.json
{
"compilerOptions": {
"moduleResolution": "classic",
"target": "es5",
"module": "es2015",
"lib": [
"es2015",
"es2016",
"es2017",
"dom"
],
"strict": true,
"sourceMap": true,
"declaration": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declarationDir": "dist/typings",
"outDir": "dist/lib",
"typeRoots": [
"node_modules/@types"
]
},
"include": [
"src"
]
}
webpack.config.js
var resolve = require(&#39;路径&#39;)。解决;
module.exports = {
entry: resolve(__dirname, 'src/test.ts'),
output: {
filename: 'test.js',
path: resolve(__dirname, 'dist'),
library: 'TEST',
libraryTarget: 'umd'
},
devtool: 'source-map',
resolve: {
extensions: [
'.ts',
'.tsx',
'.js'
]
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'awesome-typescript-loader'
}
]
}
};
gulpfile.js
var gulp = require("gulp");
var webpack = require('webpack');
var gulpwebpack = require("webpack-stream");
var del = require('del');
gulp.task("copy-html", function() {
return gulp.src('src/**/*.html')
.pipe(gulp.dest('dist'));
});
gulp.task("default", ["copy-html"], function() {
return gulp.src('src/**/*')
.pipe(gulpwebpack(require("./webpack.config"), webpack))
.pipe(gulp.dest('dist'));
});
gulp.task("clean", function() {
del(['dist']);
});
答案 0 :(得分:2)
您的类在TEST.TEST
而不是TEST
下公开的原因是因为您的Webpack配置中有library
选项。
通过将library
设置为非空字符串,您可以告诉Webpack将所有代码封装在名称TEST
下。因此,如果您在test.ts
中有另一个课程 - 请将其称为BLAH
- 它将在TEST.BLAH
下公开。
如果您希望全局使用所有顶级导出成员,只需删除Webpack配置中的library
选项。