const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = (env = {}, argv = {}) => { // OPS-7:devServer 实际监听地址(默认回环;WEB_HOST=0.0.0.0 才对外) const devServerHost = process.env.WEB_HOST || '127.0.0.1'; if (argv.mode !== 'production' && process.argv.includes('serve')) { console.log(`[webpack-dev-server] http://${devServerHost}:3021 (WEB_HOST=${process.env.WEB_HOST || '127.0.0.1'})`); } const isDev = argv.mode !== 'production'; const buildId = new Date().toISOString().replace(/[:.]/g, '-'); // 供应商系统(二次开发):部署在 nginx 后面(8444 → 127.0.0.1:3021,nginx 走 http 上游), // 故默认 HTTP(TLS 由 nginx 终止)。自签 HTTPS:`npm run dev:https`(等价 --env https)或 DEV_HTTPS=1。 const useDevHttps = env.https === true || process.env.DEV_HTTPS === '1'; return { mode: isDev ? 'development' : 'production', devtool: isDev ? 'source-map' : false, entry: './src/index.tsx', output: { path: path.resolve(__dirname, 'dist'), filename: isDev ? 'bundle.js' : 'bundle.[contenthash:8].js', chunkFilename: isDev ? '[name].bundle.js' : '[name].bundle.[contenthash:8].js', publicPath: '/', clean: true, }, optimization: { splitChunks: isDev ? false : { chunks: 'all', maxInitialRequests: 25, cacheGroups: { // initial only:避免懒路由依赖(framer-motion/jsbarcode)被抬进首包 vendors vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendors', chunks: 'initial', priority: 10, }, xlsx: { test: /[\\/]node_modules[\\/]xlsx[\\/]/, name: 'xlsx', chunks: 'async', priority: 20, }, framerMotion: { test: /[\\/]node_modules[\\/]framer-motion[\\/]/, name: 'motion', chunks: 'async', priority: 20, }, jsbarcode: { test: /[\\/]node_modules[\\/]jsbarcode[\\/]/, name: 'barcode', chunks: 'async', priority: 20, }, }, }, runtimeChunk: isDev ? false : 'single', }, performance: isDev ? false : { // xlsx 为按需加载的导入导出模块;主入口是包含 React 与基础样式的管理端壳。 // 预算按当前架构分别设置,仍会在体积继续明显增长时报警。 maxAssetSize: 450 * 1024, maxEntrypointSize: 700 * 1024, }, module: { rules: [ { test: /\.mjs$/, include: /node_modules/, type: 'javascript/auto', resolve: { fullySpecified: false, }, }, { test: /\.(ts|tsx|js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [ [ '@babel/preset-react', { runtime: 'automatic', development: isDev } ], '@babel/preset-env', '@babel/preset-typescript' ] } } }, { test: /\.css$/, use: [ isDev ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', ], }, { test: /\.(png|jpe?g|gif|webp|ico|svg)$/i, type: 'asset', // 方案 A:将小于 1MB 的图片资源内联为 dataURL,使 Webpack 产物和 Vite 产物在 OSS 上结构一致 // 消费端 HomeController 只需替换 link[href].css / script[src].js 即可预览 parser: { dataUrlCondition: { maxSize: 1024 * 1024 } } }, { test: /\.(woff2?|eot|ttf|otf)$/i, type: 'asset/resource' }, { // 兜底规则:PDF、文档、音视频等所有其他文件一律输出为独立资源文件 exclude: /\.(js|jsx|ts|tsx|mjs|css|json|html)$/i, type: 'asset/resource' } ] }, resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, extensions: ['.mjs', '.ts', '.tsx', '.js', '.jsx'] }, devServer: { // 供应商系统(二次开发)本地端口:Web 3021 → API 3022。 // 主系统(AI 生鲜配送系统)占用 Web 3015 / API 3001,两套系统需同机并存,勿改回去。 port: 3021, // OPS-7:默认只监听回环;需要局域网/手机调试时显式 `WEB_HOST=0.0.0.0`(勿默认全开) host: process.env.WEB_HOST || '127.0.0.1', /** * O-12.8:不要 'all'(DNS rebinding 可借 devServer 代理打内网)。 * 但 'auto' 只信任本机 host ⇒ 经 nginx 以域名访问 dev(8443/8444)会报 * `Invalid Host header`(2026-10-20 实测)。这里改为**显式白名单**: * 域名 + 本机;如需加主机,通过 `WEB_ALLOWED_HOSTS=a,b,c` 覆盖。 */ allowedHosts: (process.env.WEB_ALLOWED_HOSTS || 'deepseek.xdjchuanhui.com,localhost,127.0.0.1') .split(',') .map((h) => h.trim()) .filter(Boolean), // 本地预览默认 HTTPS(自签证书需浏览器点「继续访问」) server: useDevHttps ? 'https' : 'http', client: { // 允许局域网设备访问时 HMR WebSocket 正常连接(auto 适配 http/https → ws/wss); // 默认回环时用同一个 host,避免 ws://0.0.0.0 在部分浏览器连不上。 webSocketURL: `auto://${process.env.WEB_HOST || '127.0.0.1'}:0/ws`, }, static: { directory: path.resolve(__dirname, 'public'), }, historyApiFallback: { index: '/index.html', rewrites: [ { from: /^\/_p\/\d+\//, to: '/index.html' } ] }, proxy: [ { context: ['/api'], target: 'http://127.0.0.1:3022', changeOrigin: true, secure: false, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './index.html', inject: 'body', templateParameters: { BUILD_ID: buildId, // 开发:webpack HMR / 部分工具链会用到 eval;生产构建保持严格 CSP(与 nginx 一致) CSP_SCRIPT_SRC: isDev ? "'self' 'unsafe-eval'" : "'self'", }, }), ...(isDev ? [] : [new MiniCssExtractPlugin({ filename: 'styles.[contenthash:8].css' })]), { apply(compiler) { compiler.hooks.afterEmit.tap('CopyPublicConfig', () => { const fs = require('fs'); const from = path.resolve(__dirname, 'public/config.js'); const distDir = path.resolve(__dirname, 'dist'); const to = path.join(distDir, 'config.js'); fs.mkdirSync(distDir, { recursive: true }); const apiBase = " apiBase: '/api',"; const buildLine = ` buildId: '${buildId}',`; if (fs.existsSync(from)) { const base = fs.readFileSync(from, 'utf8'); const injected = base.includes('buildId:') ? base.replace(/buildId:\s*'[^']*',?/, buildLine) : base.replace(apiBase, `${apiBase}\n${buildLine}`); fs.writeFileSync(to, injected); } else { fs.writeFileSync( to, `window.__APP_CONFIG__ = window.__APP_CONFIG__ || {\n${apiBase}\n${buildLine}\n};\n` ); } fs.copyFileSync( path.resolve(__dirname, 'public/bootstrap.js'), path.resolve(__dirname, 'dist/bootstrap.js') ); }); }, }, ] }; };