如何通过JS中的WebPack包提供全局TypeScript类 [英] How to provide global TypeScript classes via WebPack bundle in JS
问题描述
我目前正在使用TypeScript。我想用TS代替JS,但是我有很多JS文件,所以我只想在TS中创建新类,并希望在我的旧JS文件atm中使用这些类。后来我想用TS替换所有的JS。
我不是100%熟悉webpack和捆绑的js文件,所以我可以使用一些帮助。
是否有机会使用gulp将TS编译成JS(已经完成 - 它能正常工作)并在不同的(旧的)JS文件中使用这些TS类?
TypeScript文件:
class Car {
seats:number;
passengers:string [];
add(passenger:string){
if(this.passengers.indexOf(passenger)=== -1){
this.passengers.push(passenger);
}
}
}
JavaScript文件:
var car = new Car();
car.seats = 5;
car.add(Pete);
正如你所说,Car是 undefined
。
如何在其他JS文件中使用我的Car类(在ts编译和webpack捆绑之后)
这是我的老东西:
gulp.task('bundle-ts-webpack' ,['compile-ts-webpack'],function(){
var tsFiles = glob.sync(config.js.tsSource);
返回webpackStream({
/ *配置选项* /
条目:tsFiles,
模块:{
规则:[
{
//测试:/\.tsx?$/,
使用:'ts-loader',
exclude:/ node_modules /
}
]
},
解析:{
extensions:[ '.tsx','.ts','.js'],
//在ts中使用ts - begin
别名:{
'TS':path.resolve(config .js.tsDest,'ts-bundle'),
'ExpertFilterHelper':path.resolve('./ static / ts /','car'),
'test':path.resolve '.static / ts /','test-globals')
}
//在ts中使用ts - end
},
//在ts中使用ts - begin
插件:[
新的webpack.ProvidePlugin({
'TS':'TS',
标识符:'car',
test:'test'
})
],
//在ts中使用ts - end
输出:{
文件名:'ts-bundle.js',
路径:路径。 resolve(config.js.tsDest,'dist')
}
})
.pipe(gulp.dest(config.js.tsDest));
});
我已经试着让这个运行,就像你在gulp.task中看到的一样,但我仍然不知道我在这里做什么。
有人能给我一个提示吗?
我已经想到了,是否我应该首先将TS编译为JS,然后通过webpack将其捆绑,但是我不知道这是否解决了我的问题。
编辑/更新:
正如Joshua Barnett所说,您可以使用expose-loader,但我仍然有一个问题我只能将一个打字稿文件添加到全局变量中。
我有三个例如:
- A.ts
- B.ts
- Car.ts
这可以正常使用:
Library.Car()
但是:
当我有另一个typecript文件/类如下所示:
- A。
- B.ts
- Car.ts
- Delivery.ts
我只能使用 Library.Delivery()
,不能使用 Library.Car()
了。
任何提示?
我目前的gulp.task:
gulp.task('compile-ts-webpack',function(){
var tsFiles = glob.sync('./ static / ts / *。ts');
console.log(require.resolve('./ static / ts / z-car-test.ts'));
返回webpackStream(
{
entry:tsFiles,// path.resolve('./ static / ts / z-car-test.ts'),
output:{
filename:'ts-bundle.js',
path:path.resolve('./ static / js / modules')
},
devtool:source-map,
resolve:{
extensions :['.tsx','.ts','.js']
},
模块:{
规则:[{
test:/\.ts | \ .tsx $ /,//require.resolve('./static/ts/z-car-test.ts'),
use:[{
loader:'expose-loader',
选项:'TSGlobals'
},{
loader:'ts-loader'
}]
// exclude:/ node_modules /
}]
}
}
).pipe(gulp.dest('./ static / js / modules'));
编辑/更新2:
如果您希望将不止一个类添加到TSGlobals中,您可以使用一些小技巧来做到这一点(我猜这是一个黑客攻击,即时通讯不知道)
我创建了一个exporter.ts,它重新导出我需要全局的所有类,以便在任何js文件中使用这些类,就像Joshua Barnett在评论中提到的那样:
// exporter.ts
从./car.ts导出{Car}从./delivery.ts中
export {Delivery};
我还需要告诉webpack将导出器typescript文件捆绑到files-array的末尾。 (Im not 100%sure why)
// gulp.task
gulp.task('compile-ts' ,['clean-ts'],function(){
var tsFiles = glob.sync('./ ts / *。ts',{ignore:['./ exporter.ts']}) ; //忽略exporter.ts
//将exporter.ts添加到数组的末尾以提供全局TSGlobals库。
tsFiles.push(config.js.tsExporterFile);
[...]
}
现在我可以在任何地方使用TSGlobals JS文件!完美地工作。
// whatever.js
var car = new TSGlobals.Car();
car.seats = 5;
car.add('Pete');
var delivery = new TSGlobals.Delivery();
delivery.doSomething( 123);
您需要使用 expose-loader ,以使您的模块在全局范围内可用。
// File:webpack.config.js
const path = require('path')
module.exports = {
context:path.resolve('src') ,
条目:'./main.ts',
模块:{
规则:[
{
test:require.resolve('./ src / main .ts'),
use:[{
loader:'expose-loader',
options:'Library'
},{
loader:'ts- loader'
}],
exclude:/ node_modules /
}
]
},
输出:{
path:path.resolve (__dirname,'dist'),
文件名:'bundle.js'
}
}
//文件:main.ts
导出类别汽车{
座位:号码;
passengers:string [];
add(passenger:string){
if(this.passengers.indexOf(passenger)=== -1){
this.passengers.push(passenger);
code
$ b $ hr
// File:main.js
var car = new Library.Car()
car.seats = 5
car.add ('Pete')
确保代码调用该模块包含在模块包之后。
<! - 文件:index.html - >
<!DOCTYPE html>
< html>
< head>
< meta charset =UTF-8>
< title> Webpack App< / title>
< / head>
< body>
< script type =text / javascriptsrc =bundle.js>< / script>< / body>
< script src =main.js>< / script>
< / html>
I am currently working on TypeScript. I want to replace JS with TS, but I have a lot of JS-Files, so that I only want to create new classes in TS and want to use these in my old JS files atm. Later on I want to replace all JS with TS.
I not 100% familiar with webpack and bundled js files, so that I could use some help.
Is there any opportunity to compile TS into JS with gulp (already done - it works) AND use these TS classes in different (old) JS files?
TypeScript file:
class Car {
seats: number;
passengers: string[];
add(passenger: string) {
if(this.passengers.indexOf(passenger) === -1) {
this.passengers.push(passenger);
}
}
}
JavaScript file:
var car = new Car();
car.seats = 5;
car.add("Pete");
As you can mention, Car is undefined
.
How can I use my Car class in other JS files? (after ts compilation and webpack bundling)
This is my old gulp task:
gulp.task('bundle-ts-webpack', ['compile-ts-webpack'], function() {
var tsFiles = glob.sync(config.js.tsSource);
return webpackStream({
/* configuration options */
entry: tsFiles,
module: {
rules: [
{
//test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
// use ts in js - begin
alias: {
'TS': path.resolve(config.js.tsDest, 'ts-bundle'),
'ExpertFilterHelper': path.resolve('./static/ts/', 'car'),
'test': path.resolve('.static/ts/', 'test-globals')
}
// use ts in js - end
},
// use ts in js - begin
plugins: [
new webpack.ProvidePlugin({
'TS': 'TS',
identifier: 'car',
test: 'test'
})
],
// use ts in js - end
output: {
filename: 'ts-bundle.js',
path: path.resolve(config.js.tsDest, 'dist')
}
})
.pipe(gulp.dest(config.js.tsDest));
});
I already tried to get this running as you can see in the gulp.task, but I still "dont know what I am doing here".
Can someone give me a hint?
I already thought, whether I should compile TS to JS first and then bundle it via webpack, but I dont know whether this solve my problem.
Edit/Updated:
As Joshua Barnett mentioned, you can use the expose-loader, but I still have a question to the expose-loader:
Can I only add one typescript file to the globals?
I have three typescript files for exmaple:
- A.ts
- B.ts
- Car.ts
This works fine: I can now use:
Library.Car()
BUT:
When I have another typescript file/class like so:
- A.ts
- B.ts
- Car.ts
- Delivery.ts
I can only use Library.Delivery()
and cannot use Library.Car()
anymore.
Any hints for that?
My current gulp.task:
gulp.task('compile-ts-webpack', function() {
var tsFiles = glob.sync('./static/ts/*.ts');
console.log(require.resolve('./static/ts/z-car-test.ts'));
return webpackStream(
{
entry: tsFiles,//path.resolve('./static/ts/z-car-test.ts'),
output: {
filename: 'ts-bundle.js',
path: path.resolve('./static/js/modules')
},
devtool: "source-map",
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
module: {
rules: [{
test: /\.ts|\.tsx$/, //require.resolve('./static/ts/z-car-test.ts'),
use: [{
loader: 'expose-loader',
options: 'TSGlobals'
}, {
loader: 'ts-loader'
}]
//exclude: /node_modules/
}]
}
}
).pipe(gulp.dest('./static/js/modules'));
Edit/Update 2:
If you want to have more than one class added to the TSGlobals you can do that with a little hack (I guess it's a hack, im not sure)
I created a exporter.ts which re-exports all classes I need to be global to use these in any js-file as Joshua Barnett mentioned in a comment:
//exporter.ts
export { Car } from "./car.ts";
export { Delivery } from "./delivery.ts";
I also need to tell webpack to bundle the exporter typescript file at the end of the files-array. (Im not 100% sure why)
//gulp.task
gulp.task('compile-ts', ['clean-ts'], function() {
var tsFiles = glob.sync('./ts/*.ts', {"ignore":['./exporter.ts']}); // Ignore exporter.ts
//add the exporter.ts to the end of the array to provide the global TSGlobals Library.
tsFiles.push(config.js.tsExporterFile);
[...]
}
Now I can use TSGlobals in any JS-file! Works perfectly.
//whatever.js
var car = new TSGlobals.Car();
car.seats = 5;
car.add('Pete');
var delivery = new TSGlobals.Delivery();
delivery.doSomething("123");
解决方案 You need to make use of the expose-loader in order to make your module available through the global scope.
// File: webpack.config.js
const path = require('path')
module.exports = {
context: path.resolve('src'),
entry: './main.ts',
module: {
rules: [
{
test: require.resolve('./src/main.ts'),
use: [{
loader: 'expose-loader',
options: 'Library'
}, {
loader: 'ts-loader'
}],
exclude: /node_modules/
}
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
}
// File: main.ts
export class Car {
seats: number;
passengers: string[];
add(passenger: string) {
if(this.passengers.indexOf(passenger) === -1) {
this.passengers.push(passenger);
}
}
}
// File: main.js
var car = new Library.Car()
car.seats = 5
car.add('Pete')
Make sure the code calling the module is included after the module bundle.
<!-- File: index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
<script type="text/javascript" src="bundle.js"></script></body>
<script src="main.js"></script>
</html>
这篇关于如何通过JS中的WebPack包提供全局TypeScript类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!