You need to enable JavaScript to run this app. 如何配置Webpack让HtmlWebpackPlugin注入的script标签src为绝对路径
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Webpack让HtmlWebpackPlugin注入的script标签src为绝对路径

问题原因

你遇到的路径问题由Webpack静态资源路径配置导致,和Babel无关:Babel仅负责JS语法转译,不参与HTML的script标签注入逻辑,注入逻辑由html-webpack-plugin实现。
之前修改entry配置无效的原因:entry配置的是Webpack打包的入口源文件路径,和最终注入到HTML里的资源访问路径没有关联,所以修改entry无法解决路径问题。


解决方案

方案1:全局配置publicPath(推荐)

在webpack.config.js的output节点新增publicPath配置,值为你需要的静态资源根路径即可:

  • 如果需要生成 <script defer src="/main.js"></script>,配置如下:
module.exports = {
  // 其余配置保持不变
  output: {
    path: path.join(__dirname, 'dist'),
    filename: "[name].js",
    publicPath: '/' // 新增这一行
  }
}
  • 如果需要生成 <script defer src="/dist/main.js"></script>,把publicPath的值改为'/dist/'即可。

方案2:单独给html-webpack-plugin配置publicPath

如果不想修改全局静态资源路径,可以只在html-webpack-plugin的配置项里新增publicPath:

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html",
  publicPath: '/' // 按需修改为对应路径即可
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 16:15:10