Angular 2 生产包文件太大

标签 angular bundle

当我 bundle 主文件时,我使用 webpack bundle 我的 angular 2 项目。文件太大,文件大小约8M。然后每当我刷新我的页面时,浏览器将需要很长时间来加载和执行 javascript 文件。 我想可能有太多我不需要的文件,但我怎样才能找到它并将它从我的 bundle 文件中踢出来呢? 谢谢你给我一些建议或帮助。

这是我的 webpack 配置的主要部分: webpack.common.js:

const webpack = require('webpack');
const helpers = require('./helpers');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

module.exports = {
    baseUrl: './',
    entry: {
        // 'polyfills': './src/polyfills.ts',
        // 'vendor': './src/vendor.ts',
        'main': './src/main.ts'
    },
    resolve: {
        extensions: ['', '.ts', '.js', '.json'],
        root: helpers.root('src'),
        modulesDirectories: ['node_modules'],
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader', 'angular2-template-loader'],
                exclude: [/\.(spec|e2e)\.ts$/]
            },
            {
                test: /\.json$/,
                loader: 'json-loader'
            },
            {
                test: /\.css$/,
                loaders: ['raw-loader']
            },
            {
                test: /\.html$/,
                loader: 'raw-loader',
                exclude: [helpers.root('src/index.html')]
            },
            {
                test: /\.scss$/,
                loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
            },
            {
                test: /\.(jpg|png|gif)$/,
                loader: 'file'
            },
            {
                test: /.(png|woff(2)?|eot|ttf|svg)$/,
                loader: 'url-loader'
            }
        ]

    },
    plugins: [
        new ForkCheckerPlugin(),
        // new CopyWebpackPlugin([
        //     {from: 'src/assets', to: 'assets'},
        //     {from: 'src/app/i18n', to: 'app/i18n'},
        //     {from: 'src/loading.css', to: 'loading.css'},
        //     {from: 'src/fonts', to: 'fonts'},
        //     {from: 'src/favicon.ico', to: ''},
        //     {from: 'src/img', to: 'img'}]),
        new HtmlWebpackPlugin({
            template: 'src/index.html',
            chunksSortMode: 'dependency'
        })
    ],

    node: {
        global: 'window',
        crypto: 'empty',
        process: true,
        module: false,
        clearImmediate: false,
        setImmediate: false
    }

};

webpack.prod.js

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
/**
 * Webpack Plugins
 */
const webpack = require('webpack');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';

module.exports = webpackMerge(commonConfig, {
    devtool: 'source-map',

    output: {
        path: helpers.root('dist'),
        filename: '[name].bundle.js',
        chunkFilename: '[id].chunk.js'
    },

    plugins: [
        // new webpack.NoErrorsPlugin(), // 如果出现任何错误 就终止构建
        // new DedupePlugin(), // 检测完全相同(以及几乎完全相同)的文件 并把它们从输出中移除
        // new webpack.optimize.CommonsChunkPlugin({
        //     name: ['polyfills', 'vendor', 'main'].reverse()
        // }),
        new UglifyJsPlugin({
            beautify: false,
            mangle: { screw_ie8 : true, keep_fnames: true },
            compress: { screw_ie8: true, warnings: false },
            comments: false
        }),
        // new ExtractTextPlugin('[name].[hash].css'), // 把内嵌的 css 抽取成玩不文件 并为其文件名添加 hash 后缀 使得浏览端缓存失效
        new DefinePlugin({ // 定义环境变量
            'process.env': {
                ENV: JSON.stringify(ENV)
            }
        }),
    ],

    htmlLoader: {
        minimize: true,
        removeAttributeQuotes: false,
        caseSensitive: true,
        customAttrSurround: [
            [/#/, /(?:)/],
            [/\*/, /(?:)/],
            [/\[?\(?/, /(?:)/]
        ],
        customAttrAssign: [/\)?\]?=/]
    },

    tslint: {
        emitErrors: true,
        failOnHint: true,
        resourcePath: 'src'
    },

    node: {
        global: 'window',
        crypto: 'empty',
        process: false,
        module: false,
        clearImmediate: false,
        setImmediate: false
    }

});

我删除了我的 vendor.ts 文件 这是我的 polyfills.ts

// This file includes polyfills needed by Angular 2 and is loaded before
// the app. You can add your own extra polyfills to this file.
// Added parts of es6 which are necessary for your project or your browser support requirements.
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';
import 'core-js/es6/reflect';
import 'core-js/es6/weak-map';
import 'core-js/es6/weak-set';

import 'core-js/es7/reflect';
import 'zone.js/dist/zone';

最佳答案

前几天我正在尝试使用 Angular 2,我遇到了和你一样的问题,我的 vendor.js 是 6M,这是一个简单的“Hello World”应用程序...

我发现以下帖子对理解我们应该如何处理这个问题(目前)有很大帮助: http://blog.mgechev.com/2016/06/26/tree-shaking-angular2-production-build-rollup-javascript/

他在 1.5M 的应用程序上使用了多种优化和压缩技术(预编译、treeshake、缩小、 bundle 和 gzip),将其大小减小到仅 50kb。

看看吧,希望对你有帮助! :)

编辑: 从那以后我用 Angular 运行了几次,对我来说最好的工作方法是使用 angular-cli,当我写这篇文章时它是 v1.0,当你用 --prod 运行构建时它确实如此我在原始帖子中写的所有内容 + 一个普通的网络服务器都会压缩你的文件。我的完整网站不到 1MB,他有很多功能,还有很多第三方的东西。

关于Angular 2 生产包文件太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651526/

相关文章:

php - 如何定义一个实体,它通常被多个 bundle 使用?

java - BundleActivator 方法未在 OSGi 中得到通知

angular - 如何处理在 Angular 4 中丢失深度导入

node.js - 路径在 tsconfig.app.json 中没有按预期工作

javascript - Angular2 [src] 动态加载图像时导致 404 错误

ios - UIImage 在主包中加载错误图像

angular - 如何获取最后发出的 Observable

http - Angular2 : detect error from HTTP post

ios - 在 iPhone 开发中使用 bundle 有什么好处?

ios - Swift 在发布时将音频文件添加到 bundle 中