You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Webpack5 Dev Server搭配WordPress时出现Cannot GET /错误

Webpack Dev Server配置问题排查(WordPress主题场景)

我接手的站点用了臃肿老旧的Webpack配置,自己之前没Webpack使用经验,想搭一个更轻量易懂的配置,要包含webpack-dev-server。现在模板的package.json里有大量过时依赖,也找不到相关解释。

已经配好了watch命令(还没测监听),现在想配start命令——就算用旧配置,我也从没成功运行过webpack-dev-server。

我把webpack.config.js和webpack.dev.js合并,用npm run start启动。站点基于WordPress,根目录是./dist,Webpack处理后的js/sass/css输出到./dist/resources。目前WP主题模板只有一个带基础HTML的index.php。

把devServer.static.publicPath设为/时,页面显示./dist(WP根目录)的目录结构;设为/wp-content/themes/wp-boilerplate/时,页面出现Cannot GET /错误。想问哪里配置错了?


现有配置文件

webpack.config.js

// webpack.config.js
const path = require('path');
const postcssPresetEnv = require('postcss-preset-env');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');

const rootOutputPath = path.resolve(__dirname, 'dist');
const outputPaths = {
  js: 'resources/js',
  css: 'resources/css',
};

module.exports = {
  entry: {
    app: './src/entries/app.entry.js',
  },
  output: {
    filename: `${outputPaths.js}/[name].bundle.js`,
    chunkFilename: `${outputPaths.js}/[name].chunk.js`,
    path: rootOutputPath,
    clean: true,
  },
  plugins: [
    // Copy images to dist folder
    // These are not processed by webpack
    new CopyPlugin({
      patterns: [
        {
          from: './src/images',
          to: 'resources/images',
        },
      ],
    }, {
      ignore: ['*.DS_Store', '*.gitkeep', '*.gitignore', '*.git', '.keep'],
    }),
    // Extract CSS to separate files
    new MiniCssExtractPlugin({
      filename: `${outputPaths.css}/[name].bundle.css`,
      chunkFilename: `${outputPaths.css}/[id].bundle.css`,
      ignoreOrder: false,
    }),
    // Lint JS files
    new ESLintPlugin(),
  ],
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              [
                '@babel/preset-env',
                {
                  targets: 'defaults'
                }
              ]
            ]
          }
        }
      },
      {
        test: /\.(sa|sc|c)ss$/i,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: [
                  postcssPresetEnv(),
                ],
              },
            },
          },
          {
            loader: "sass-loader",
            options: {
              // Prefer `dart-sass`
              implementation: require("sass"),
            },
          },
          {
            loader: 'sass-resources-loader',
            options: {
              resources: [
                './src/scss/settings/*.scss',
                './src/scss/tools/**/*.scss',
              ],
            },
          }
        ],
      },
    ],
  },
  optimization: {
    minimizer: [
      new CssMinimizerPlugin(),
    ],
  },
};

webpack.dev.js

// webpack.dev.js
const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
      publicPath: '/wp-content/themes/wp-boilerplate/',
    },
    compress: false,
    allowedHosts: 'all',
    open: true,
  }
};

package.json

// package.json
{
  "name": "wp-boilerplate",
  "version": "1.0.0",
  "description": "wp-boilerplate",
  "main": "index.js",
  "private": true,
  "scripts": {
    "start": "webpack serve --config webpack.config.js --config webpack.dev.js --merge",
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --config webpack.config.js --config webpack.dev.js --merge --watch"
  },
  "repository": {
    "type": "git",
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.21.3",
    "@babel/preset-env": "^7.20.2",
    "babel-loader": "^9.1.2",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.3",
    "css-minimizer-webpack-plugin": "^4.2.2",
    "eslint": "^8.36.0",
    "eslint-webpack-plugin": "^4.0.0",
    "mini-css-extract-plugin": "^2.7.3",
    "postcss": "^8.4.21",
    "postcss-loader": "^7.0.2",
    "postcss-preset-env": "^8.0.1",
    "sass": "^1.59.3",
    "sass-loader": "^13.2.0",
    "sass-resources-loader": "^2.2.5",
    "style-loader": "^3.3.2",
    "webpack": "^5.76.1",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.12.0"
  }
}

问题分析与修复方案

核心问题

  1. publicPath路径不匹配:你设置的/wp-content/themes/wp-boilerplate/是WordPress主题的标准路径,但你的Webpack输出目录是./dist(即WordPress根目录),dev server会去./dist/wp-content/themes/wp-boilerplate/找文件,而你的主题入口index.php实际在./dist根目录,导致找不到资源。
  2. 缺少索引文件配置:当publicPath设为/时,dev server把./dist作为根目录,但未指定默认加载index.php,所以默认显示目录结构。

修复步骤

1. 调整devServer.static配置

修改webpack.dev.js,让dev server正确识别WordPress根目录,并支持PHP入口文件:

// webpack.dev.js
const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
      publicPath: '/',
      watch: true, // 监听dist目录下的PHP文件变化
    },
    // 配置路由回退,确保访问根路径时加载index.php
    historyApiFallback: {
      index: '/index.php',
    },
    compress: false,
    allowedHosts: 'all',
    open: true,
    // 若本地有PHP服务器(如XAMPP/WAMP,端口设为8080),添加proxy转发PHP请求
    proxy: {
      '/': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        bypass: (req) => {
          // 静态资源直接由dev server处理,PHP请求转发到本地服务器
          if (!req.url.includes('.php')) return req.url;
        }
      }
    }
  }
};

2. 补充Webpack output的publicPath

在webpack.config.js的output中添加publicPath,确保资源引用路径正确:

output: {
  filename: `${outputPaths.js}/[name].bundle.js`,
  chunkFilename: `${outputPaths.js}/[name].chunk.js`,
  path: rootOutputPath,
  clean: true,
  publicPath: '/', // 确保浏览器能正确加载dist下的资源
},

3. 运行PHP服务器

Webpack-dev-server无法处理PHP动态请求,需要本地搭建PHP服务器(如XAMPP),将站点根目录指向./dist,端口设为8080(和proxy配置一致)。

为什么之前的配置出错?

  • 设publicPath: '/wp-content/themes/wp-boilerplate/'时,dev server认为静态资源根路径是该地址,但index.php在./dist根目录,访问/时找不到对应文件,返回Cannot GET /。
  • 设publicPath: '/'时,dev server把./dist作为根目录,但未配置historyApiFallback指定默认索引文件,所以显示目录结构而非加载index.php。

内容的提问来源于stack exchange,提问作者Bagseye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:57:04