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

Webpack修改index.html中JavaScript文件的src路径问题

解决方案

1. 修改Webpack Output的publicPath

在你的Webpack配置文件(比如webpack.config.js)中,找到output配置段,将publicPath设置为./:

const path = require('path');

module.exports = {
  // ...其他配置项
  output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist'), // 你的构建输出目录
    publicPath: './' // 关键:设置为相对路径
  }
};

这个配置会让Webpack生成资源引用时,使用相对于当前HTML文件的路径,而非带admin/的前缀路径。

2. 同步html-webpack-plugin的配置

如果项目使用html-webpack-plugin自动生成index.html,需要确保插件的publicPath也同步设置为./,避免冲突:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...其他配置项
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html', // 你的HTML模板路径
      publicPath: './' // 显式指定相对路径
    })
  ]
};

部分场景下插件会继承Webpack的output.publicPath,但显式设置能确保路径生成符合预期。

3. Strapi自定义Webpack配置适配

如果是在Strapi项目中自定义构建配置,需要在Strapi的Webpack扩展文件(通常是config/webpack.config.js)中修改:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = (config, webpack) => {
  // 更新output的publicPath
  config.output.publicPath = './';
  
  // 找到并更新html-webpack-plugin的配置
  const htmlPlugin = config.plugins.find(plugin => plugin instanceof HtmlWebpackPlugin);
  if (htmlPlugin) {
    htmlPlugin.options.publicPath = './';
  }
  
  return config;
};

原理说明

问题的核心是Webpack默认的publicPath被设置为admin/或绝对路径,导致生成的脚本引用自动带上了admin/前缀。将publicPath改为./后,所有资源引用都会以index.html所在的根目录为基准,直接引用同目录下的文件,路径就会变成./file.js的正确形式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:45:11