Django,ReactJS,Webpack热重载

Sim*_*son 5 django reactjs webpack-dev-server

我一直在尝试借助webpack 4在django中设置一个react组件。

为了让我起步,我仔细阅读了以下内容:

结合使用Webpack和Django +热重载React组件作为奖励

教程:带有React的Django REST(Django 2.0和一些测试)

这两个演练都非常好。最后,即使我确实使用了django 1.11,也可以通过跟随第二个链接来使它正常工作。

我跟随第二个链接后遇到的问题是,使用webpack-dev-server时,热重装不起作用。问题在于,虽然可以读取main.js,但django无法读取webpack-dev-server的输出文件(给出404错误)。我读过dev-server文件默认情况下仅存在于内存中。

为了克服热重载文件上出现错误404的问题,请安装软件包write-file-webpack-plugin以将每次重载写出。然后将webpack-config.js更改为(我删除了几行以使其更短...。):

var path = require('path');
//webpack is not needed since I removed it from plugins
//const webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var WriteFilePlugin =require('write-file-webpack-plugin');
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
    ]
  },
  entry: [
          './frontend/src/index',
          ],
  output: {
    path: path.join(__dirname, 'frontend/static/frontend'),
    // Changing the name from "[name]-[hash].js" to not get 1000 files in the static folder.
    filename: 'hotreloadfile.js'
  },
  plugins: [
    //This line writes the file on each hot reload
    new WriteFilePlugin(),
    //This can be removed.
    //new webpack.HotModuleReplacementPlugin(),
    new BundleTracker({filename: './webpack-stats.json'})
  ],
  mode:'development',
};
Run Code Online (Sandbox Code Playgroud)

在我的package.json中,我在script标记之间有以下一行:

"start": "webpack-dev-server --config ./webpack.config.js",
Run Code Online (Sandbox Code Playgroud)

在django中,我webpack-loader在settings.py中安装了以下几行:

STATIC_URL = '/static/'

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'frontend/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json')
        }
}
Run Code Online (Sandbox Code Playgroud)

最后,在名为index.js的根组件中,不需要该 module.hot.accept();

您看到这种方法有什么缺点吗?除了我必须安装另一个软件包之外?我为什么不可以使用它new webpack.HotModuleReplacementPlugin()

如果有人对我的方法有疑问,如果有一些不清楚的步骤,我很乐意扩展我的问题。

dis*_*ver 1

如果你在 React 中开发前端,在 Django 中开发后端,这里是另一种方法。我有 django 服务器在端口 8000 上运行,react 服务器在端口 3000 上运行。

如果我"proxy": "http://localhost:8000"在 React 代码的 package.json 中添加行,则 localhost:3000 将执行热重载,而 api 调用将转到 localhost:8000。