Webpack Dev Server不会热重载,需要手动构建Webpack

时间:2019-06-27 20:32:53

标签: javascript webpack

这是小型React应用的子组件中的一些渲染代码示例:

<React.Fragment>
  <h1>From Tab Section</h1>
  <h2>update 2</h2> // doesn't display in the browser
  <p>update 3</p> // also doesn't display
</React.Fragment>

区别在于,在编写h1标签之后,我重新构建了Webpack。

进一步的测试证实,重建bundle.js并刷新其注入的index.html页面上的浏览器是查看更新的唯一方法。

我认为我具有如文档所示的热重装设置。在另一篇SO帖子中,我在启动命令中添加了--inline。但是仍然需要手动构建和重新启动开发服务器。

这里还需要什么?

// package.json
"scripts": {
    "test": "jest --watch",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open --inline",
    "build": "webpack"
  },
  "devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/preset-react": "^7.0.0",
    "babel-jest": "^24.8.0",
    "babel-loader": "^8.0.6",
    "jest": "^24.8.0",
    "webpack": "^4.35.0",
    "webpack-cli": "^3.3.5",
    "webpack-php-loader": "^0.5.0"
  },
  "dependencies": {
    "dotenv": "^8.0.0",
    "dotenv-webpack": "^1.7.0",
    "history": "^4.9.0",
    "lodash": "^4.17.11",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-redux": "^7.1.0",
    "react-router-dom": "^5.0.1",
    "redux": "^4.0.1",
    "save-dev": "^2.0.0",
    "webpack-dev-server": "^3.7.2"
  }

// webpack.config.js
const webpack = require("webpack");
const dotenvWebpack = require("dotenv-webpack");
const path = require("path");

module.exports = {
  entry : {
    './adminSettingsArea' :
      './adminSettingsArea/src/index.jsx'
  },
  output : {
    filename : '[name]/bundle.js',
    path : path.resolve(__dirname),
  },
  devtool: 'inline-source-map',
  devServer : {
    contentBase : './adminSettingsArea',
    hot : true
  },
  plugins : [
    new webpack.HotModuleReplacementPlugin(),
    new dotenvWebpack()
  ],
  module : {
    rules : [
      {
        test : /\.(js|jsx)$/,
        exclude : [/node_modules/, /vendor/],
        use : {
          loader : "babel-loader",
          options : {
            presets : [
              '@babel/preset-env',
              "@babel/preset-react"
            ]
          },
        }
      }
    ],
  },
};

1 个答案:

答案 0 :(得分:0)

通过将index.html文件移动到与其余内容Webpack在内存中更新相同的文件夹(./adminSettingsArea/src)中来解决。

以前,此索引文件比contentBase值低一级。结果,webpack最初可以加载index.html文件,但不能加载/ src子文件夹中的jsx文件。

另外,请参见下面的示例,了解我在输出路径中遇到的另一个问题。

entry : {
    'adminArea' :
      './adminSettingsArea/src/index.jsx'
  },
  output : {
    filename : 'shared/[name].bundle.js', // for some reason I need to assign the subfolder here instead of arg 2 in the next line
    path : path.resolve(__dirname, ''),
  },
  devtool: 'inline-source-map',
  devServer : {
    contentBase : './adminSettingsArea/src',
    hot : true
  },