Webpack 配置 (webpack.config.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', },externals: {react: 'react', 'react-dom': 'react-dom', },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(), new CssMinimizerPlugin(), ],},resolve: {extensions: ['.js', '.jsx'], },
};
- 外部依赖:在 externals 中配置不打包的依赖(例如 React 和 ReactDOM),并在 peerDependencies 中声明它们,以确保用户在使用你的库时会安装这些依赖。
Package.json 配置
{"name": "my-library","version": "1.0.0","main": "dist/my-library.js", "module": "dist/my-library.esm.js", "files": ["dist"],"scripts": {"build": "webpack --mode production"},"dependencies": {},"peerDependencies": {"react": "^17.0.0", "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"}
}