我一直在按照以下教程来让Django和ReactJS工作:
http://geezhawk.github.io/using-react-with-django-rest-framework
我开始了一个全新的Django项目,添加了一个名为home
的应用程序,但除了本教程中概述的内容之外别无其他。
无论如何,当我编译JS时,它会创建一个大约21,500行和800kb的文件。我的ReactJS文件只有大约20行,并且没有其他JS可以从Django应用程序中找到。它似乎是在virtualenv
或其他东西中编译依赖项。无论如何要防止这种情况?
webpack.config.js
//require our dependencies
var path = require('path')
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
//the base directory (absolute path) for resolving the entry option
context: __dirname,
//the entry point we created earlier. Note that './' means
//your current directory. You don't have to specify the extension now,
//because you will specify extensions later in the `resolve` section
entry: './assets/js/index',
output: {
//where you want your compiled bundle to be stored
path: path.resolve('./assets/bundles/'),
//naming convention webpack should use for your files
filename: '[name]-[hash].js',
},
plugins: [
//tells webpack where to store data about your bundles.
new BundleTracker({filename: './webpack-stats.json'}),
//makes jQuery available in every module
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
module: {
loaders: [
//a regexp that tells webpack use the following loaders on all
//.js and .jsx files
{test: /\.jsx?$/,
//we definitely don't want babel to transpile all the files in
//node_modules. That would take a long time.
exclude: /node_modules/,
//use the babel loader
loader: 'babel-loader',
query: {
//specify that we will be dealing with React code
presets: ['react']
}
}
]
},
resolve: {
//tells webpack where to look for modules
modulesDirectories: ['node_modules'],
//extensions that should be used to resolve modules
extensions: ['', '.js', '.jsx']
}
}
答案 0 :(得分:3)
React和jQuery是你的软件包的一部分。是的,你只写了大约20行代码,但你也将React导入你的项目,因为你只有一个条目定义,您导入的所有内容都将捆绑到一个捆绑包中(这可能适合您的需求)。更重要的是,您的Webpack配置还会全局导入jQuery。您可以将依赖关系分解为自己的包或多个包,并在需要时根据需要加载它们。
您正在捆绑React的开发版本。当Webpack运行并捆绑您的项目时,它会根据process.env
评估为“开发”还是“生产”执行不同的操作”。我们的想法是在开发过程中简化开发并缩短构建时间。在React的情况下,您的开发版本包含大量注释和额外检查(更多千字节),因为您的环境未设置为“生产”。
树摇晃,重复数据删除和缩小是你的朋友。我会让你看看这些,但基本上,树摇动(Webpack 2的一部分)使你只能捆绑您实际使用的库的一部分。在webpack 1.x中,有一个重复数据删除插件可以删除重复的代码部分,缩小将会缩小代码。您可以将Webpack配置设置为仅在生产构建环境中运行时才运行这些步骤。
尝试使用此方法将插件部分更换为:
plugins: [
...(process.env === 'production' ? [
// set webpack process env to production
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') },
}),
new webpack.optimize.DedupePlugin(), // webpack 1.x only
new webpack.optimize.UglifyJsPlugin({ comments: false }),
] : []),
//tells webpack where to store data about your bundles.
new BundleTracker({filename: './webpack-stats.json'}),
//makes jQuery available in every module
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
],