一些类.ts:
export class SomeClass{
constructor(){}
}
index.html:
<script src="SomeClass.js"></<script> // compiled to es5
<script>
var someClass = new SomeClass(); //SomeClass is not defined
</script>
我正在运行 es5,所以我无法执行任何导入操作。
在普通的 javascript 中你可以这样做:
(function(global){
function SomeClass() {
}
global.IfcModel = IfcModel;
})(window);
如何在窗口中公开 typescript 中的类?
转译后的js文件:
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SomeClass = /** @class */ (function () {
function SomeClass() {
}
return SomeClass;
}());
exports.SomeClass = SomeClass;
});
最佳答案
您是使用模块的“一半”。为此,要么不使用模块(删除 export
),要么始终如一地使用它们(例如,让您的第二个脚本成为导入类的模块)。现在就像半次握手......
如果您将库发布为 TypeScript,请注意 TypeScript 处理模块(v1.8 及更高版本),因此使用模块不会强制您的用户使用 Webpack 或类似工具; more in this blog post .
如果您希望他们能够在不使用模块的情况下使用它,请不要在库中使用模块。
关于javascript - 将类暴露给全局, typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46756128/