[英]Creating a typescript library that can be used in browser and nodejs
I would like to create a library that can be used in both - browser and nodejs. 我想创建一个可以在浏览器和nodejs中使用的库。 For the sake of the argument let's say this is my library: 为了论证,让我们说这是我的库:
export default class MyClass {
public getString(): string {
return "Message";
}
}
ES2015 modules are not supported by browsers as of now and I don't want to depend on requirejs or any other module loader when in browser - I would like this library to be consumed just by including the generated .js file using the script
tag. 到目前为止,浏览器不支持ES2015模块,我不希望在浏览器中依赖requirejs或任何其他模块加载器 - 我希望通过使用script
标记包含生成的.js文件来使用此库。 It feels that what I want can be achieved by using internal modules (I don't want to pollute the global namespace). 感觉我想要的东西可以通过使用内部模块来实现(我不想污染全局命名空间)。 However when I wrap my code in namespace
/ module
I am having a hard time to get it compiled to as commonjs module. 但是,当我将代码包装在namespace
/ module
时,我很难将其编译为commonjs模块。
What is the proper way of achieving what I want? 实现我想要的正确方法是什么? Or, may be, I am getting completely off the rails here being a typescript and javascript noob? 或者,可能是,我完全脱离了轨道这里是打字稿和javascript noob?
I think what you need is UMD
. 我认为你需要的是UMD
。 With tsconfig.json
containing 使用tsconfig.json
{
"compilerOptions": {
"module": "umd"
},
}
generated JavaScript will look like this: 生成的JavaScript将如下所示:
(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";
var MyClass = (function () {
function MyClass() {
}
MyClass.prototype.getString = function () {
return "Message";
};
return MyClass;
}());
exports.__esModule = true;
exports["default"] = MyClass;
});
It works in node (CommonJS) as well as with browsers (CommonJS, AMD). 它适用于节点(CommonJS)以及浏览器(CommonJS,AMD)。 To allow users of your library to just include it through script
tag, you need module bundler like Webpack , Browserify or Rollup . 要允许您的库的用户通过script
标记包含它,您需要模块捆绑器,如Webpack , Browserify或Rollup 。 Those will produce UMD definition with global export, so default export of main file of your library will be available as some variable in global scope. 这些将使用全局导出生成UMD定义,因此库的主文件的默认导出将作为全局范围内的某个变量提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.