我目前正在進行一個項目,我需要配置WebPack。在該項目中,我們也在使用ReactJS和語義UI。這裏是webpack.config.js:WebPack加載所有語義UI組件
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']
},
};
在資產/ JS/index.jsx文件,我們只是有這些import語句:
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束分析儀插件,我們得到這樣的:
由於你看到圖中的紅色矩形,所有的反應組件都被捆綁成home.js文件,儘管我只是將impor ted Button
組件來自assets/js/index.js文件,這就是爲什麼輸出文件變得太大。
是否有任何方法來捆綁需要的組件?
UPDATE
閱讀@Alexander Fedyashov答案,我安裝巴貝爾-插件,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']
},
};
現在一切正常,只需要加載組件。
我做了你所說的並更新了帖子,但babel-plugin-lodash沒有刪除未使用的組件。請檢查我是否做錯了什麼。謝謝 –
你不檢查SUIR倉庫中的示例配置,你應該爲plugin定義用於轉換的導入:'[「lodash」,{「id」:[「lodash」,「semantic-ui-react」]}]' –
哦,我忘了。它正在工作,謝謝。 –