Webpack - 由FullCalendar

时间:2017-03-31 14:28:00

标签: webpack fullcalendar

我正在使用Fullcalendar& Moment.js使用JSON数据构建简单的交互式日历。我使用Webpack 2将我的JS捆绑到一个文件中。下面是我的webpack.config.js文件的简化版本(完整的东西加载的远不止这个)。

var webpack = require('webpack');

var bower_dir = __dirname + '/library/bower_components';

var config = {
    resolve: {
        alias: {
            jquery: bower_dir + '/jquery/src/jquery.js',
            vue: bower_dir + '/vue/dist/vue.js',
            fullCalendar: bower_dir + '/fullcalendar/dist/fullcalendar.js',
            moment: bower_dir + '/moment/moment.js',
        }
    },

    entry: {
        app: './library/js/main.js'
    },

    output: {
        path: __dirname + '/dist/library/js',
        filename: "bundle.js"
    },

    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            Vue: 'vue'
        }),
    ],

    module: {
        noParse: /moment.js/
    }

};

module.exports = config;

我注意到我的捆绑文件在包含这两个文件后大大增加了文件大小。我在Moment here中阅读了类似的问题,并实施了这些更改,将未压缩的捆绑包大小从2.13MB减少到1.83MB。

当通过Webpack Visualiser运行webpack --json的输出时,我注意到完整日历仍然对文件大小的大部分负责,比任何其他库我都要多。包括(23.7%,第二高是jQuery为15.8%,然后是Vue.JS为15.4%)。

我想知道是否有人知道我可以减少此文件大小的任何方式?我目前在生产中运行webpack -p,将尺寸减小到656kB,但这似乎仍然很多。

enter image description here

3 个答案:

答案 0 :(得分:1)

使用webpack配置文件并配置IgnorePlugin以排除所有区域设置文件:

var webpack = require('webpack')

module.exports = {
  ...
  plugins: [
    // Ignore all locale files of moment.js
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  ...
};

您可能需要一些区域设置。要拥有它,您可以在代码中导入它们:

import moment from 'moment'
import 'moment/locale/fr'

答案 1 :(得分:0)

您是否考虑过为jQuery和Fullcalendar使用CDN版本?首先,那些更有可能被用户的浏览器缓存(肯定是jQuery,因为很多站点都使用它),并且这些库的缓存将独立于你的开发周期,这可能加速重复页面上的事情负载。不知道如何进行缓存,但由于Fullcalendar和jQuery是bundle的一部分,每次更改bundle时,用户也必须重新下载这些lib。使用现有CDN可以消除该问题。

此外,如果您使用babel进行JS转换,也许可以尝试使用Webpack 2并使用一些最小的babel配置调整来获得tree-shaking,这也可能会减少捆绑包的大小。

答案 2 :(得分:0)

<强>配置

entry: {
  moment: bower_dir + '/moment/moment.js',
  fullcalendar: bower_dir + '/fullcalendar/dist/fullcalendar.js',
  app: './library/js/main.js'
},
plugins: [
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Vue: 'vue'
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: ['moment', 'fullcalendar', 'manifest']
  })
]

假设您绝对需要从您的应用程序服务器(而不是CDN)提供这些库依赖项,那么我们需要进行代码拆分并确保我们将需要/导入的公共库分开你的代码库。

或者,您也可以通过缩小捆绑包来缩小文件大小,但我假设您已经知道如何做到这一点。