Комментарии React в пакете, созданном с помощью webpack, содержат код и делают блок поставщика слишком большим - PullRequest
0 голосов
/ 01 августа 2020

Я использую webpack, а размер производственного блока поставщика составляет ~ 350 тыс.

Просматривая его, я нахожу такие комментарии (усеченные):

** @license React v16.13.1
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var n=r(0),o=r(50),a=r(59);function i(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}if(!n)throw Error(i(227));function l(e,t,r,n,o,a,i,l,s){var c=Array.prototype.slice.call(arguments,3);try{t.apply(r,c)}catch(e){this.onError(e)}}var s=!1,c=null,d=!1,u=null,m={onError:function(e){s=!0,c=e}};function f(e,t,r,n,o,a,i,d,u){s=!1,c=null,l.apply(m,arguments)}var p=null,g=null,b=null;function h(e,t,r){var n=e.type||"unknown-event";e.currentTarget=b(r),function(e,t,r,n,o,a,l,m,p){if(f.apply(this,arguments),s){if(!s)throw Error(i(198));var g=c;s=!1,c=null,d||(d=!0,u=g)}}(n,t,void 0,e),e.currentTarget=null}var x=null,v={};function y(){if(x)for(var e in v)... keeps on and on and on...

vendor bundle

I am fine with the legal text, but can't quite figure out why there is commented code as well (the last line, above): this commented code accounts for ~250k of the vendor bundle. The lines underlined in red are 10th of thousands of characters long. I can remove them manually since they are comments, and the app functions as I expect.

I tried to use the terser and uglify plugins with the comments option set to true, but no luck.

This is my webpack configuration:

const frontend = {
  entry: {
    index: './frontend/app_container.jsx',
    manifest: './manifest.webmanifest',
    image1: './assets/image/toaste_192.png',
    image2: './assets/image/toaste_512.png',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'public'),
    publicPath: '/',
  },
  resolve: {
    alias: {
      component: path.resolve(__dirname, 'frontend/component/'),
      store: path.resolve(__dirname, 'frontend/store/'),
      lib: path.resolve(__dirname, 'frontend/lib/'),
      context: path.resolve(__dirname, 'frontend/context/'),
      image: path.resolve(__dirname, 'assets/image/'),
    },
    extensions: ['*', '.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react'],
            plugins: ['@babel/plugin-proposal-object-rest-spread'],
          },
        },
        resolve: {
          extensions: ['*', '.js', '.jsx'],
        },
      },
      {
        test: /\.(png|svg|jpg|gif|webmanifest)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
  plugins: [
    /*
    moment.js is gigantic and loads locales for all languages. This only keeps english (customizable)
     */
    new MomentLocalesPlugin(),
    /*
    This plugin lists all the output chunks (bundles) and injects them in the index.html
    by programmatically adding the <script src="bundle[hash].js"></script> tags.
    */
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'index_template.html'),
      filename: path.resolve(__dirname, 'index.html'),
    }),
    (() => {
      const options = { swSrc: path.resolve(__dirname, 'service_worker.js') };
      if (process.env.WEBPACK_MODE === 'development') {
        options.maximumFileSizeToCacheInBytes = 500000000;
      }
      return new InjectManifest(options);
    })(),
    new CompressionPlugin({
      filename: '[file].br',
      algorithm: 'brotliCompress',
      test: /\.(js)$/,
    }),
  ],
};

Есть какие-нибудь сведения о том, что я делаю неправильно?

1 Ответ

0 голосов
/ 02 августа 2020

Мой вопрос был у сбитого с толку человека. Что я действительно хотел, но не знал, так это проанализировать содержимое пакета.

Я не знал о существовании таких инструментов, как webpack-bundle-analyzer . Это позволило мне понять, что bootstrap CSS занимает более трети размера пакета. Используя purge css -webpack-plugin , я мог сократить его с 157 КБ до 4,81 КБ!

...