Webpack Dev Server无法热加载,需要手动进行Webpack构建。

3
这是一个小型React应用程序中子组件的示例渲染代码: ```html

这里是一些示例渲染代码,在小型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个回答

1

将index.html文件移动到与其他内容相同的文件夹(./adminSettingsArea/src)中,webpack会在内存中更新。之前,该索引文件与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
  },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接