【发布时间】:2018-10-06 07:22:49
【问题描述】:
我一直在尝试借助 Webpack 4 在 Django 中设置一个 React 组件。
为了让我开始,我阅读并阅读:
-
Using Webpack transparently with Django + hot reloading React components as a bonus
-
Tutorial: Django REST with React (Django 2.0 and a sprinkle of testing)
这两个演练都很棒。最后,尽管我使用的是 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 中,脚本标签中有以下行:
"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() 一起使用?
【问题讨论】:
-
你能解决这个问题吗? @西蒙
-
是的,我设法通过上述过程解决了这个问题。不知道它是否仍然有效,但有时会得到一些支持,因此该方法似乎仍然有效。
-
@GwynBleidD 这个问题没有答案。他们在问他们的方法是否合适以及为什么
webpack.HotModuleReplacementPlugin()对他们不起作用。这两个都是一个完全有效的问题。碰巧的是,他们为解决问题而采取的经过深入研究的方法对其他人非常有帮助..
标签: django reactjs webpack-dev-server