我正在寻找一个可靠的指南来提供有关如何在Django项目中设置React的详细信息。我已经阅读了django-webpack-loader自述文件,以及它引用的网站here。两者都很容易遵循,但我遇到围绕webpack.config.js文件的问题。我要么得到编译错误,要么没有渲染。
以下是链接1
中的webpack.config.js文件var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
entry: './assets/js/index',
output: {
path: path.resolve('./assets/webpack_bundles/'),
filename: "[name]-[hash].js"
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'})
]
}
这是产生的错误
ERROR in ./assets/js/index.js
Module parse failed: Unexpected token (4:13)
You may need an appropriate loader to handle this file type.
| var App = require('./app')
|
| React.render(<App/>, document.getElementById('react-app'))
以下是链接2
中的webpack.config.js文件var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: './assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs
output: {
path: path.resolve('./assets/bundles/'),
filename: "[name]-[hash].js",
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
],
},
resolve: {
modules: ['node_modules', 'bower_components'],
extensions: ['.js', '.jsx']
},
}
这不会产生错误,并且脚本标记中的django模板中会显示相应的javascript bunfle文件,但不会呈现任何内容。
我的强项是Python,而不是JS,所以我遇到了诊断问题的问题。设置在settings.py中正确完成,我确实有一个webpack-stats.json,但实际的javascript部分已经关闭了。我已经用npm安装了以下内容。
○ react
○ webpack
○ webpack-bundle-tracker
○ babel
○ babel-loader
○ babel-core
○ babel-eslint
○ babel-preset-es2015
○ babel-preset-react
○ babel-preset-stage-0
○ babel-plugin-transform-decorators-legacy
○ eslint
这是我的assets / js / index.js文件
var React = require('react')
var App = React.createClass({
render: function(){
return <h1>Hello, world.</h1>
}
})
React.render(<App/>, document.getElementById('react-app'))
这是django模板
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="react-app"></div>
{% render_bundle 'main' %}
</body>
</html>
除此之外,在遵循django-webpack-loader指南时,settings.py文件,我的views.py和urls.py都是正确的。