webpack 热更新 只对改变 CSS 有效 改变 HTML 页面会刷新 没用其他框架。

发布于 2022-09-05 21:24:14 字数 1841 浏览 14 评论 0

写了一个很简单的demo,HMR 开启成功,但是只对改变 CSS 有效,改变 HTML 只会刷新页面,没有达到热替换的效果。

global webpack version 3.3.0
Mac OS 10.11.6

this is my package.json file:

{
  "name": "demo-hmr",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --hot --inline webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "css-loader": "^0.28.7",
    "style-loader": "^0.18.2",
    "webpack": "^3.5.6",
    "webpack-dev-server": "^2.7.1"
  }
}

this is my webpack.config.js file:

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  }
}

this is my main.js file:
I change dom in this file, just change innerHTML of divv, then page will refresh, not i want for.

import app from './app.css'

var divv = document.createElement('div')
divv.innerHTML = "Hello webpack"
document.body.appendChild(divv)

this is my app.css file:

body {
    background-color: yellow;
}

this is my index.html file:

<html>
    <body>
      <h1>Hello World!</h1>
    <script type="text/javascript" src="bundle.js"></script>
    </body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

⒈起吃苦の倖褔 2022-09-12 21:24:15

HTML不会热更新。只有js,css这些被webpack管理的模块化东西才会热更新。

帅气称霸 2022-09-12 21:24:15

是没配置html的loader吧,像这样:

module: {
    rules: [
        {
            test: /\.html$/,
            use: 'xxxxxx'
        },
        ...
    ],
    ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文