如何用webpack打包umd模块并测试打包结果
时间: 2024-02-16 15:03:53 浏览: 22
你可以按照以下步骤使用Webpack打包UMD模块并测试打包结果:
1. 安装Webpack和Webpack CLI:
```
npm install webpack webpack-cli --save-dev
```
2. 创建一个新的Webpack配置文件`webpack.config.js`,并配置入口文件和输出文件的路径:
```javascript
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-library.js',
library: 'MyLibrary',
libraryTarget: 'umd'
}
};
```
这里的`library`和`libraryTarget`选项将使Webpack生成UMD模块。
3. 创建一个UMD模块的源文件`src/index.js`,并导出一个函数:
```javascript
function hello(name) {
return `Hello, ${name}!`;
}
module.exports = {
hello
};
```
4. 在`package.json`文件中添加一个`build`脚本,用于运行Webpack打包:
```json
{
"scripts": {
"build": "webpack --mode production"
}
}
```
5. 运行`npm run build`命令打包UMD模块。
6. 创建一个测试用例`test/index.html`,并在其中引入打包后的UMD模块:
```html
<!DOCTYPE html>
<html>
<head>
<title>MyLibrary Test</title>
</head>
<body>
<script src="../dist/my-library.js"></script>
<script>
console.log(MyLibrary.hello('world'));
</script>
</body>
</html>
```
7. 在浏览器中打开`test/index.html`文件,查看控制台输出结果。
如果一切顺利,你应该能够看到控制台输出`Hello, world!`。