2016-06-28 88 views
0

我有一個MEAN應用程序客戶端在anular2構建webpack。Angular2 + Webpack:如何優化供應商包

當我爲服務器提供初始請求的index.html時,由於供應商模塊JS文件大於3MB,因此在生產應用程序時需要加載時間5或6甚至更多秒。

我如何優化這件事 我想分開供應商的JS文件。以下是我的webpack.config.js

const webpack = require('webpack'); 
const production = process.env.NODE_ENV === "production"; 
const autoprefixer = require('autoprefixer'); 
const path = require("path"); 

const config = { 

    entry: { 
    'app': './client/app.ts', 
    'vendor': './client/vendor.ts' }, 

    debug: !production, 

    devtool: production ? null : "source-map", 

    output: { 
    path: "./dist", 
    filename: "bundle.js" }, 

    plugins: [ 
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js') ], 

    resolve: { 
    extensions: ['', '.ts'] }, 

    module: { 
    loaders: [ 
     { test: /\.ts$/, loader: 'ts-loader' }, 
     { test: /\.html$/, loader: 'raw'}, 
     { test: /\.scss$/, include: [ path.resolve(__dirname, 'client/app/components') ], loader: 'style!css!postcss!sass' } 
    ], 
    noParse: [ path.join(__dirname, 'node_modules', 'angular2', 'bundles') ] }, postcss: [ autoprefixer ] }; 

module.exports = config; 

以下是我​​文件

import 'core-js/es6'; 
import 'core-js/es7/reflect'; 
require('zone.js/dist/zone'); 

import 'ts-helpers'; 

import '@angular/platform-browser-dynamic'; 
import '@angular/core'; 
import '@angular/common'; 
import '@angular/http'; 
import '@angular/router'; 

import 'socket.io-client'; 

// RxJS 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/mergeMap'; 

import './assets/vendor/bootstrap'; 
import './assets/vendor/fontawesome.scss'; 

大廈項目,我可以得到 bundle.jsbundle.map.js包含我的應用程序的js vendor.bundle.js and 個vendor.bundle.map.js將包含其他第三方JS

我想編譯這個vendor.js每個庫單獨以及所有SCSS應該在單獨的style.css在ditribution進行編譯。

謝謝大家。

+0

這個問題有什麼好運?我也試圖找到答我的問題http://stackoverflow.com/questions/43500349/angular2-bundle-node-modules-only-and-not-application-code –

回答

1

我可以看到一些方面進行改進:

  1. 我看不到你的代碼中的任何微小插件,所以它會給你 巨大的推動作用。見UglifyJsPlugin
  2. 您直接添加所有角模塊(甚至可能不需要它們):

    import {Component} from '@angular/core'; 
    
  3. 擁有進口:

    import '@angular/platform-browser-dynamic'; 
    import '@angular/core'; 
    import '@angular/common'; 
    import '@angular/http'; 
    import '@angular/router'; 
    

    需要像時,最好是剛剛導入具體的事情像上面一樣劃分,你將能夠獲得即將到來的Webpack 2的好處。最重要的部分是:

ES6模塊的靜態特性允許一些新的優化。例如,在許多情況下,可以檢測哪些導出已被使用,哪些未被使用。

如果webpack可以肯定地說沒有使用導出,它會省略將導出公開給其他模塊的語句。稍後,最小化者可以將該聲明標記爲未使用並省略它。

我認爲所有這一切可以使您的生產應用程序更薄,無需拆分庫。