我目前正在做一个项目,我需要配置WebPack。在项目中,我们还使用了 ReactJS和Semantic-UI。这是webpack.config.js:
var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var BundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
context: __dirname,
entry: {
react: ["react", "react-dom"],
home: './assets/js/index.jsx',
},
output: {
path: path.resolve('./assets/bundles/'),
filename: "[name].js",
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
new webpack.optimize.CommonsChunkPlugin({
names: ["react"],
}),
new webpack.optimize.CommonsChunkPlugin({
name: "home",
chunks: ['home'],
filename: "[name]-[hash].js",
}),
new BundleAnalyzer(),
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: { presets: ["es2015", "react"] }
},
],
},
resolve: {
modules: ['node_modules', 'bower_components'],
extensions: ['*', '.js', '.jsx']
},
};
在assets/js/index.jsx文件中,我们只有这些导入语句:
import React from "react";
import ReactDOM from 'react-dom';
import { Button } from 'semantic-ui-react';
通过运行 webpack 命令,它会输出两个文件:
- react.js:779 KB
- 主页-[some_hash_number].js:1.5 MB
使用webpack-bundle-analyzer插件,我们得到:
正如您在图片中看到的红色矩形,所有语义 UI反应组件都捆绑到home.js文件中,尽管我只是从assets/js/index.jsButton
文件中导入组件,这就是输出文件变得太大的原因。
有什么方法可以捆绑所需的组件吗?
更新
阅读@Alexander Fedyashov 的答案,我安装了babel-plugin-lodash并相应地更新了 webpack.config.js:
var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var BundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
context: __dirname,
entry: {
react: ["react", "react-dom"],
home: './assets/js/index.jsx',
},
output: {
path: path.resolve('./assets/bundles/'),
filename: "[name].js",
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
new webpack.optimize.CommonsChunkPlugin({
name: "react",
}),
new webpack.optimize.CommonsChunkPlugin({
name: "home",
chunks: ['home'],
filename: "[name]-[hash].js",
}),
new BundleAnalyzer(),
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: ["lodash", { "id": ["lodash", "semantic-ui-react"] }],
presets: ["es2015", "react"],
}
},
],
},
resolve: {
modules: ['node_modules', 'bower_components'],
extensions: ['*', '.js', '.jsx']
},
};
现在一切正常,只加载了需要的组件。