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

新手上路,请多包涵

写了一个很简单的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>
阅读 5.6k
2 个回答

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

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

module: {
    rules: [
        {
            test: /\.html$/,
            use: 'xxxxxx'
        },
        ...
    ],
    ...
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题