我一直在尝试使用Webpack 4来在Django中设置React组件。
为了让我开始,我阅读了以下内容:
这两个教程都非常好。最终,我通过遵循第二个链接获得了几乎可以工作的结果,尽管我使用Django 1.11。
在遵循第二个链接后我的问题是,在使用webpack-dev-server
时热重新加载不起作用。问题在于Django无法读取webpack-dev-server
的输出文件(给出404错误),而main.js
可以被读取。我已经阅读到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',
};
在我的package.json
文件中,在script标签中有以下代码:
"start": "webpack-dev-server --config ./webpack.config.js",
在Django中,我使用以下settings.py
代码行安装了webpack-loader
:
STATIC_URL = '/static/'
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'frontend/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json')
}
}
最后,在我称为index.js
的根组件中,我不需要module.hot.accept();
行。
您是否认为这种方法有任何缺点?除了我不得不安装另一个包之外?
为什么我不能通过 new webpack.HotModuleReplacementPlugin()
使其工作?
webpack.HotModuleReplacementPlugin()
对他们无效。这两个问题都是完全合理的。恰好他们采取了经过深入研究的方法来解决问题,对其他人非常有帮助。 - Sabito stands with Ukraine