有两种方式
一、npm-util
先安装
npm install umd-util
安装完后,我们写一个js module保存为src/foo.js
'use strict';开始编译成umd格式
function Foo() {}
const umdify = require('umd-util');好了,在dist目录中会多一个foo.js的文件,我们打开看看
umdify.sync('src/foo.js', {
destination: 'dist'
});
(function(root, factory) {你们看已经编译成umd的格式了。
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;
}));
高级用法请参看https://www.npmjs.com/package/umd-util
二、webpack
先安装webpack和webpack-cli
npm install webpack webpack-cli --save-dev
创建一个项目 npm init,打开package.json,可以看到下面的依赖。
{编写一个module模块为 src/add.js
"devDependencies": {
"webpack": "^5.36.2",
"webpack-cli": "^4.6.0"
}
}
// src/add.js修改webpack.config.js配置文件
module.exports = function add(a, b) {
return a + b;
};
// webpack.config.js使用webpack来编译一下
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',
},
};
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
网友回复
js如何流式输出ai的回答并折叠代码块,点击代码块右侧可预览代码?
ai大模型如何将文章转换成可视化一目了然的图片流程图图表?
大模型生成html版本的ui原型图和ppt演示文档的系统提示词怎么写?
rtsp视频直播流如何转换成websocket流在h5页面上观看?
为啥coze会开源工作流agent coze studio?
如何检测网页是通过收藏夹打开的?
python如何实现类似php的http动态脚本请求处理响应代码?
js如何实现类似php的http动态脚本请求处理响应代码?
trae与solo有啥区别不同?
vue如何让ai动态生成问卷调查多步骤表单式收集基础信息自动规划执行任务?