js
复制代码
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
entry: './src/index.js', // 入口文件
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-library.js', // 输出文件
library: 'MyLibrary', // 库名称
libraryTarget: 'umd', // 支持多种模块化格式
globalObject: 'this', // 解决 UMD 在浏览器和 Node.js 环境下的兼容性问题
},
externals: {
react: 'react', // 不打包 React,使用外部的 React
'react-dom': 'react-dom', // 不打包 ReactDOM
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.(png|jpg|gif|svg)$/,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
type: 'asset/resource',
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'my-library.css',
}),
],
optimization: {
minimize: true,
minimizer: [
new TerserPlugin(), // 压缩 JavaScript
new CssMinimizerPlugin(), // 压缩 CSS
],
},
resolve: {
extensions: ['.js', '.jsx'], // 解析这些扩展名的文件
},
};
js
复制代码
{
"name": "my-library",
"version": "1.0.0",
"main": "dist/my-library.js", // CommonJS 入口
"module": "dist/my-library.esm.js", // ESModule 入口
"files": [
"dist"
],
"scripts": {
"build": "webpack --mode production"
},
"dependencies": {
// 需要打包的依赖
},
"peerDependencies": {
"react": "^17.0.0", // 作为 peer dependency
"react-dom": "^17.0.0"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.0",
"css-loader": "^6.0.0",
"mini-css-extract-plugin": "^2.0.0",
"terser-webpack-plugin": "^5.0.0",
"css-minimizer-webpack-plugin": "^3.0.0",
"webpack": "^5.0.0",
"webpack-cli": "^4.0.0"
}
}