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

如何为Webpack生成的Bundle添加defer属性

给Webpack自动注入的Bundle脚本添加defer属性的方法

Webpack打包React应用时,自动注入script标签的功能通常由HtmlWebpackPlugin实现,以下是几种给注入的脚本添加defer属性的可行方案:

方案一:Webpack 5+ 直接配置scriptLoading

Webpack 5及配套的HtmlWebpackPlugin新增了scriptLoading选项,直接设置为'defer'即可为所有自动注入的脚本添加defer属性:

修改webpack.config.js中的插件配置:

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

module.exports = {
  // ...其他Webpack配置项
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html', // 你的React应用模板文件路径
      scriptLoading: 'defer' // 核心配置
    })
  ]
};

方案二:自定义HTML模板(兼容旧版本)

如果使用Webpack 4及以下版本,或者需要更精细的控制,可以关闭自动注入,手动在模板中添加带defer属性的脚本标签:

  1. 先在HtmlWebpackPlugin配置中关闭自动注入:
new HtmlWebpackPlugin({
  template: './public/index.html',
  inject: false
})
  1. 在你的HTML模板文件(如public/index.html)中,使用Webpack提供的模板变量手动注入bundle文件:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React App</title>
</head>
<body>
  <div id="root"></div>
  <!-- 遍历所有JS bundle并添加defer属性 -->
  <% htmlWebpackPlugin.files.js.forEach(chunk => { %>
    <script defer src="<%= chunk %>"></script>
  <% }) %>
</body>
</html>

方案三:借助第三方插件扩展

使用script-ext-html-webpack-plugin插件可以更灵活地给指定脚本添加属性:

  1. 安装插件:
npm install script-ext-html-webpack-plugin --save-dev
  1. 在webpack.config.js中配置插件:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

module.exports = {
  // ...其他配置
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    }),
    new ScriptExtHtmlWebpackPlugin({
      defer: [/main\.bundle/] // 匹配main.bundle开头的脚本文件,添加defer属性
    })
  ]
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:00:57