+
95
-

回答

有两种方式

一、npm-util

先安装

npm install umd-util

安装完后,我们写一个js module保存为src/foo.js

'use strict';
function Foo() {}

开始编译成umd格式

const umdify = require('umd-util');

umdify.sync('src/foo.js', {
destination: 'dist'
});

好了,在dist目录中会多一个foo.js的文件,我们打开看看

(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.Foo = factory();
}
}(this, function() {
'use strict';
function Foo() {}
return Foo;
}));

你们看已经编译成umd的格式了。

高级用法请参看https://www.npmjs.com/package/umd-util

二、webpack

先安装webpack和webpack-cli

npm install webpack webpack-cli --save-dev

创建一个项目 npm init,打开package.json,可以看到下面的依赖。

{
"devDependencies": {
"webpack": "^5.36.2",
"webpack-cli": "^4.6.0"
}
}

编写一个module模块为 src/add.js

// src/add.js
module.exports = function add(a, b) {
return a + b;
};
修改webpack.config.js配置文件
// webpack.config.js
module.exports = {
entry: './src/add.js',
output: {
filename: 'add.js',
library: {
type: 'umd',
name: 'add',
},
// prevent error: `Uncaught ReferenceError: self is not define`
globalObject: 'this',
},
};

使用webpack来编译一下
npx webpack

输出提示

asset add.js 399 bytes [compared for emit] [minimized] (name: main)
./src/add.js 57 bytes [built] [code generated]
我看看模块的目录结构

tree -I node_modules
.
├── dist
│ └── add.js
├── package.json
└── src
└── index.js
2 directories, 3 files

在dist目录中已经生成了add.js了

我们先用commonjs来调用这个模块试试

node
> const add = require('./dist/add');
> add(1, 2);

再使用AMD在浏览器中运行试试

<!-- amd.html -->
<h1></h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script>
window.requirejs(['dist/add'], function (add) {
document.querySelector('h1').innerText = add(1, 2);
});
</script>

ok,在nodejs中和浏览器中都能运行了。

参考文章:https://remarkablemark.org/blog/2016/09/22/webpack-build-umd/#commonjs

网友回复

我知道答案,我要回答