Webpack多模块场景如何为students和staff设置不同publicPath值
解决方案
你可以选择以下两种方式实现不同模块的差异化publicPath配置:
方案1:单配置调整(适配现有结构)
核心思路是移除全局公共publicPath,给每个HTML模板插件单独配置资源路径前缀,同时按需适配静态资源loader的路径规则:
const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // 若不需要处理单独抽离css可忽略该引入 const path = require('path'); module.exports = { entry: { students: [ './students/css/students.css', './students/js/students.js', './students/templates/students/index.pug' ], staff: [ './staff/css/index.css', './staff/js/index.js', './staff/templates/index.pug', ] }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', // 移除全局写死的publicPath }, module: { rules: [ // 示例:css处理规则,若用style-loader内联css可忽略该配置,使用MiniCssExtractPlugin抽离css需按模块匹配publicPath { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: (resourcePath) => { return resourcePath.includes('/students/') ? '/students/' : '/' } } }, 'css-loader' ] }, // pug、图片、字体等其他资源loader规则按自身需求补充 ] }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css' }), new HtmlWebpackPlugin({ filename: 'index.html', template: './students/templates/students/index.pug', chunks: ['students'], // 单独配置students模块的publicPath publicPath: '/students/' }), new HtmlWebpackPlugin({ filename: 'staff.html', template: './staff/templates/index.pug', chunks: ['staff'], // 单独配置staff模块的publicPath publicPath: '/' }) ] };
方案2:多配置隔离(更推荐,无耦合)
直接导出两份独立的webpack配置,各自管理自身的构建规则,完全避免不同模块的配置互相影响:
const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); // 导出配置数组,每个元素对应一个模块的独立构建配置 module.exports = [ // students模块配置 { entry: { students: [ './students/css/students.css', './students/js/students.js', './students/templates/students/index.pug' ] }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', publicPath: "/students/" }, plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', template: './students/templates/students/index.pug', chunks: ['students'], }) ] // students模块专属的其他loader、插件规则自行补充 }, // staff模块配置 { entry: { staff: [ './staff/css/index.css', './staff/js/index.js', './staff/templates/index.pug', ] }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', publicPath: "/" }, plugins: [ new HtmlWebpackPlugin({ filename: 'staff.html', template: './staff/templates/index.pug', chunks: ['staff'], }) ] // staff模块专属的其他loader、插件规则自行补充 } ]
内容的提问来源于stack exchange,提问作者RSKMR
相关产品推荐
相关产品推荐

