我写了一个NPM模块。让我们说这就是:
class MyModule {
// bla bla
};
我想以通用的方式导出MyModule
,以便人们可以在浏览器中以任何 3种最常用的方法导出它:
使用ES6导入:
// If a transpiler is configured (like Traceur Compiler, Babel, Rollup or Webpack):
import MyModule from 'my-npm-module';
使用CommonJS Imports
// If a module loader is configured (like RequireJS, Browserify or Neuter):
const MyModule = require('my-npm-module');
只需在HTML中引用脚本文件:
<script ="/node_modules/my-npm-module/index.js">
<script>
const module = new MyModule();
</script>
我该怎么做?我该如何导出MyModule
?
答案 0 :(得分:5)
您正在寻找的是通用模块定义(UMD)模式。它在此处定义:https://github.com/umdjs/umd
这是一种模式,它提供了一种干净的方式,可以将您的模块提供给以各种方式使用模块的不同环境。
标准模式是:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['dependency'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('dependency'));
} else {
// Browser globals (root is window)
root.returnExports = factory(root.dependency);
}
}(this, function (dependency) {
// Use dependency in some fashion.
return {
// Your Module goes here
};
}));
如果您正在使用grunt或gulp或webpack,您会发现有一个插件可以为您包装这样的模块;实际上,它已经是webpack的核心。
答案 1 :(得分:1)
来自yeoman https://github.com/umdjs/umd/blob/master/templates/returnExports.js
的一个例子// create a simplified module returnExport that has no dependency
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(this, function () {
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return {};
}));
我建议也要看一下着名Q库的源代码
答案 2 :(得分:0)
尝试:
(function(exports) {
class MyModule {
// ...
}
exports = MyModule;
})(typeof exports === 'undefined' ? this['MyModule'] = {} : exports)
然后,如果您要发布NPM包,请按照官方文档:https://docs.npmjs.com/getting-started/publishing-npm-packages