我正在编写一个具有以下结构的Typescript库:
和文件内容:
restApi.class.ts
import { restApiOptions } from '../models/rest.options.model';
import { StoreMethods } from '../routes/store.methods.class';
import { UserMethods } from '../routes/user.methods.class';
export class RestApi {
public storeRest: StoreMethods;
public userRest: UserMethods;
constructor(private restApiOptions: restApiOptions) {
.....
}
setLanguage(langId: number){
.....
}
}
store.methodds.class.ts
import { Observable } from 'rxjs';
import { restApiOptions } from '../models/rest.options.model';
import { routeMethods } from '../core/routeMethods.interface';
export class StoreMethods implements routeMethods {
constructor(private restApiOptions: restApiOptions) {
.....
}
setLanguage(languageId: number){
......
}
getStore(storeId: number): Observable<any> {
.....
}
}
和public_api.ts
export { RestApi } from './lib/core/restApi.class'
该库旨在用作Angular2 +项目中的依赖项,因此我有一个带有下一个配置的tsconfig文件来转换它并生成定义文件
{
"compilerOptions": {
"outDir": "./dist/",
"declaration": true,
"module": "commonjs",
"target": "es5",
"lib": [
"es2017",
"dom",
"es2015",
"es5",
"es6"
]
},
"exclude": [
"node_modules",
]
}
我的问题是这个库也需要以“老式的方式”在一个简单的es5 javascript项目中使用,也就是说,在脚本标记中包含javascript库文件并以这样的方式使用它:
var myRestApi = new RestApi(options)
我正在使用webpack将所有文件合并到一个bundle.js文件中,但在生成此文件并将其包含在项目中后,我无法访问RespApi类。
这是我的webpack.config.js
const path = require('path');
module.exports = [{
entry: './src/public_api.ts',
module: {
rules: [{
test: /\.tsx?$/,
use: [{
loader : 'ts-loader',
options:{
configFile : 'tsconfig.json'
}
}],
exclude: /node_modules/
}]
},
resolve: {
extensions: ['.ts', '.js', '.tsx']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dev')
}
}];
有没有办法将库转换为单个javascript文件并从全局访问RestApi类?
在webpack的网站上有一个官方的guide。我建议你阅读它。
这是备忘单。在webpack.config.js
中添加两个字段。
webpackConfig.output.library = "RestApi"
webpackConfig.output.libraryTarget = "var"
虽然有一个短暂的到来。因为您将模块导出为public_api.js
中的命名模块,所以用户只能通过window.RestApi.RestApi
访问它。没有试验,我不完全确定如何解决这个问题。