Webpack, кажется, вызывается несколько раз - PullRequest
0 голосов
/ 04 февраля 2020

Я не могу использовать объект env или argv в webpack.config. js, потому что он вызывается несколько раз и очищает эти объекты.

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
require('dotenv').config();

console.log(process.env);

const createConfig = (argv) => {
  const __DEV__ = argv.mode === 'development';
  const __PROD__ = argv.mode === 'production';
  const __NODE_ENV__ = argv.mode;

  const rules = [
    {
      test: /\.(js|jsx|tsx|ts)$/,
      enforce: 'pre',
      loader: 'eslint-loader',
      exclude: /node_modules/,
      options: {
        emitError: true,
        configFile: './.eslintrc.js',
      },
    },
    {
      test: /\.(js|jsx|ts|tsx)?$/,
      use: ['babel-loader'],
    },
    {
      type: 'javascript/auto',
      test: /\.json$/,
      loader: 'json-loader',
    },
    {
      test: /.scss$/,
      use: [
        __PROD__ ? MiniCssExtractPlugin.loader : 'style-loader',
        'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
        { loader: 'postcss-loader' },
        'sass-loader',
      ],
    },
    {
      test: /\.less$/,
      use: [
        { loader: 'style-loader' },
        { loader: 'css-loader' },
        {
          loader: 'less-loader',
          options: {
            javascriptEnabled: true,
            modifyVars: {
              'font-family': `'Open Sans', sans-serif`,
            },
          },
        },
      ],
    },
    {
      test: /\.css$/,
      use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
    },
    {
      test: /\.woff(\?.*)?$/,
      loader:
        'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff',
    },
    {
      test: /\.woff2(\?.*)?$/,
      loader:
        'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2',
    },
    {
      test: /\.otf(\?.*)?$/,
      loader:
        'file-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype',
    },
    {
      test: /\.ttf(\?.*)?$/,
      loader:
        'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream',
    },
    {
      test: /\.eot(\?.*)?$/,
      loader: 'file-loader?prefix=fonts/&name=[path][name].[ext]',
    },
    {
      test: /\.svg(\?.*)?$/,
      loader:
        'url-loader?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml',
    },
    {
      test: /\.(png|jpg)$/,
      loader: 'url-loader?limit=8192',
    },
  ];

  const stagePlugins = {
    test: [new BundleAnalyzerPlugin()],
    development: [
      new HtmlWebpackPlugin({
        template: path.resolve('./src/index.html'),
        filename: 'index.html',
        inject: 'body',
        minify: false,
        chunksSortMode: 'auto',
      }),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin(),
    ],
    production: [
      new MiniCssExtractPlugin({
        filename: '[name].[hash].css',
        chunkFilename: '[name].[hash].css',
      }),
      new HtmlWebpackPlugin({
        template: path.resolve('./src/index.html'),
        filename: 'index.html',
        inject: 'body',
        minify: {
          collapseWhitespace: true,
        },
        chunksSortMode: 'auto',
      }),
      new webpack.ProvidePlugin({
        fetch: 'exports-loader?self.fetch!whatwg-fetch',
      }),
    ],
  };

  const stageConfig = {
    development: {
      devtool: '',
      stats: {
        chunks: false,
        children: false,
        chunkModules: false,
        colors: true,
      },
    },
    production: {
      devtool: 'source-map',
      stats: {
        chunks: true,
        chunkModules: true,
        colors: true,
      },
    },
  };

  const optimization = {
    optimization: {
      splitChunks: {
        chunks: 'all',
        minChunks: 2,
      },
      minimizer: [
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              unused: true,
              dead_code: true,
            },
            warnings: false,
          },
          sourceMap: true,
        }),
        new OptimizeCSSAssetsPlugin({}),
      ],
    },
    performance: {
      hints: false,
    },
  };

  const webpackConfig = {
    mode: __DEV__ ? 'development' : 'production',
    name: 'client',
    target: 'web',
    devtool: stageConfig[__NODE_ENV__].devtool,
    stats: stageConfig[__NODE_ENV__].stats,
    module: {
      rules: [...rules],
    },
    ...optimization,
    resolve: {
      modules: ['node_modules', 'src'],
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
    },
  };

  webpackConfig.entry = {
    app: [path.resolve(__dirname, 'src/index.tsx')].concat(
      'webpack-hot-middleware/client?path=/__webpack_hmr',
    ),
  };

  webpackConfig.output = {
    filename: '[name].[hash].js',
    chunkFilename: '[name].[hash].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  };

  webpackConfig.plugins = [
    new webpack.DefinePlugin({
      __DEV__,
      __PROD__,
    }),
    ...stagePlugins[__NODE_ENV__],
  ];

  return webpackConfig;
};

module.exports = (env, argv) => {
  console.log(argv);
  return createConfig(argv);
};

Вывод файла console.log внутри module.exports -

{
  _: [],
  cache: null,
  bail: null,
  profile: null,
  color: { level: 2, hasBasic: true, has256: true, has16m: false },
  colors: { level: 2, hasBasic: true, has256: true, has16m: false },
  liveReload: true,
  'live-reload': true,
  serveIndex: true,
  'serve-index': true,
  inline: true,
  info: true,
  mode: 'development',
  open: '',
  hot: true,
  port: 3000,
  'info-verbosity': 'info',
  infoVerbosity: 'info',
  'client-log-level': 'info',
  clientLogLevel: 'info',
  host: 'localhost',
  '$0': '/Users/am/Projects/Deloitte/Deloitte.CraCmp/front/node_modules/.bin/webpack-dev-server'
}
ℹ 「wds」: Project is running at http://localhost:3000/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /Users/am/Projects/Deloitte/Deloitte.CraCmp/front
ℹ 「wdm」: wait until bundle finished: /
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
...

Так что, похоже, он работает при первом вызове npm start и затем очищается. Поэтому я не могу использовать их в своем файле Webpack.

Мои сценарии:

"scripts": {
    "start": "webpack-dev-server --mode development --open --hot --port 3000",
    "build": "webpack --mode production",
    "test": "jest --config ./jest.config.json",
    "storybook": "start-storybook -p 6006",
    "build-storybook": "build-storybook"
  },
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...