Почему Webpack / Babel добавляет React к сборке, когда она не нужна? - PullRequest
0 голосов
/ 15 января 2019

Когда я запускаю сборку и смотрю на файл preloader.bundle, я вижу, что React входит в комплект, но я не импортирую React в свой класс.

Есть способ убрать или оптимизировать конфиг?

Это связано с пресетами?

Вот мой Webpack конфиг:

const path = require('path');

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyWebpackPlugin = require('uglifyjs-webpack-plugin');

const PATH_APP = path.resolve(__dirname, "app");
const PATH_DIST = path.resolve(__dirname, "dist");
const PATH_PROJ = path.join(PATH_APP, "project");
const NODE_PATH = path.resolve(__dirname, "node_modules");

module.exports = (env, argv) => {
    console.log('ENVIRONMENT => ', argv.mode);

    const devTool = argv.mode == 'development' ? 'inline-source-map' : 'none';
    const devMode = argv.mode == 'development' ? true : false;

    let config = {
        entry: {
            preloader: './app/project/preloader.js',
            main: './app/project/index.js',
        },
        devtool: devTool,
        output: {
            path: PATH_DIST,
            filename: '[name].bundle.js'
        },
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: ['babel-loader']
                },
                {
                    test: /\.(sa|sc|c)ss$/,
                    use: [
                        devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
                        'css-loader',
                        'sass-loader'
                    ]
                }
            ]
        },
        devServer: {
            contentBase: path.join(__dirname, 'dist'),
            hot: true
        },
        resolve: {
            extensions: ['*', '.js', '.jsx'],
            alias: {
                assets: path.resolve(__dirname, './src/assets/'),
                "~": PATH_APP,
                "~fr": PATH_APP + "/alexagena",
                "~pr": PATH_APP + "/project",
                "~md": PATH_APP + "/materialdesign"
            }
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: path.join(__dirname, 'app', 'project', 'template.ejs'),
                appMountId: 'app-root-container',
                title: 'Test',
                excludeChunks: ['main']
            }),
            new MiniCssExtractPlugin({
                filename: devMode ? '[name].css' : '[name][hash].css',
                chunkFilename: devMode ? '[id].css' : '[id].[hash].css'
            }),
            new CleanWebpackPlugin([
                    'dist',
                ], {
                    root: __dirname,
                    exclude: ['data', 'fonts', 'media', 'mock', '.htaccess', 'web.config'],
                    verbose: true,
                    dry: false
                }
            ),
        ]
    }

    if (devMode)
        config.plugins.push(new webpack.HotModuleReplacementPlugin())

    return config;
}

А вот файл Preloader:

/*
 * Preloader
 *
 */
class Preloader {

  constructor() {
    //params
    this._container = document.body;

    window.appStarted = false;
  }

  // Public
  //-------------------------------------------------------
  _startPreloader() {

  }

  _updatePercent(e, percent) {

  }

  _preloaderFinished(e) {
    app.trigger("preloadcomplete");

    if (!window.appStarted) {
      setTimeout(() => {
        app.trigger("preloadcomplete");
      }, 100);
    }
  }
}

//auto initiate
var __preloader = new Preloader();

Также .babelrc:

{
    "presets": [
        ["env", {
            "modules": false,
            "targets": {
                "browsers": [
                    "chrome >= 43",
                    "ie >= 10",
                    "safari >= 7"
                ]
            }
        }],
        "react"
    ],
    "plugins": ["react-hot-loader/babel", "transform-object-rest-spread", "react-html-attrs"]
}

Сгенерированный prealoader.bundle:

!function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=36)}({0:function(module,exports,__webpack_require__){"use strict";var evalAllowed=!1;try{eval("evalAllowed = true")}catch(e){}var platformSupported=!!Object.setPrototypeOf&&evalAllowed;module.exports=__webpack_require__(17)},1:function(e,r,t){"use strict";e.exports=t(18)},14:function(e,r,t){"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/var n=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,u=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var r={},t=0;t<10;t++)r["_"+String.fromCharCode(t)]=t;if("0123456789"!==Object.getOwnPropertyNames(r).map(function(e){return r[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,r){for(var t,l,i=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),a=1;a<arguments.length;a++){for(var c in t=Object(arguments[a]))o.call(t,c)&&(i[c]=t[c]);if(n){l=n(t);for(var f=0;f<l.length;f++)u.call(t,l[f])&&(i[l[f]]=t[l[f]])}}return i}},16:function(e,r){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},17:function(e,r,t){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n,o=(n=t(1))&&"object"==typeof n&&"default"in n?n.default:n,u=function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")},l=function(e,r){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!r||"object"!=typeof r&&"function"!=typeof r?e:r},i=function(e){function r(){return u(this,r),l(this,e.apply(this,arguments))}return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function, not "+typeof r);e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),r&&(Object.setPrototypeOf?Object.setPrototypeOf(e,r):e.__proto__=r)}(r,e),r.prototype.render=function(){return o.Children.only(this.props.children)},r}(o.Component);r.AppContainer=i,r.hot=function(){return function(e){return e}},r.areComponentsEqual=function(e,r){return e===r},r.setConfig=function(){},r.cold=function(e){return e}},18:function(e,r,t){"use strict";
/** @license React v16.6.1
 * react.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=t(14),o="function"==typeof Symbol&&Symbol.for,u=o?Symbol.for("react.element"):60103,l=o?Symbol.for("react.portal"):60106,i=o?Symbol.for("react.fragment"):60107,a=o?Symbol.for("react.strict_mode"):60108,c=o?Symbol.for("react.profiler"):60114,f=o?Symbol.for("react.provider"):60109,p=o?Symbol.for("react.context"):60110,s=o?Symbol.for("react.concurrent_mode"):60111,d=o?
....
...