Конфигурация webpack 4 для режима разработки путаница - PullRequest
2 голосов
/ 27 февраля 2020

Обновление: похоже, что это вовсе не было причиной - вместо этого это побочный эффект некоторого странного кода ошибки, приводящего сервер узла в режим разработки ... отлично работал в webpack 2, но с weback 4, имеющим требование mode = prod / dev - все работает не так круто, но, по крайней мере, я нашел причину сейчас, и этот вопрос, вероятно, должен был * d ie тихо смущаться ..


Я перешел с webpack 2 на webpack 4, и с режимом разработки дела идут не так, как надо.

Я успешно создал приложение в рабочем режиме, но, конечно, это не очень полезно для меня при отладке. Production успешно создает чанки и корректно загружает их в браузер, и все хорошо ..

Разработка строит только основной. js, загружает его, но не загружает ни один из чанков. чанки есть в каталоге, и консоль не показывает никаких ошибок.

Вопрос в том, что я сделал неправильно, из-за чего чанки не загружаются?

I ' Я вызываю вещи (для разработки) через пакет. json используя

"postinstall": "npm run build:dll",
"prebuild": "npm run build:clean",
"build": "cross-env REACT_APP_VERSION=$npm_package_version NODE_ENV=production webpack --mode=development --config internals/webpack/webpack.dev.babel.js --color --progress",
"build-prod": "cross-env REACT_APP_VERSION=$npm_package_version NODE_ENV=production webpack --mode=production --config internals/webpack/webpack.prod.babel.js --color -p --progress",
"build:clean": "npm run test:clean && rimraf ./build",
"build:dll": "node ./internals/scripts/dependencies.js",

Мои конфиги выглядят следующим образом: -

webpack.dev.babel. js:

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = require('./webpack.base.babel')({
  mode: 'development',
  entry: [
    path.join(process.cwd(), 'app/app.js'),
  ],

  output: {
    filename: '[name].js',
    chunkFilename: '[name].chunk.js',
    sourceMapFilename: '[file].map',
    publicPath: '/app/',
  },
  devtool: 'eval-source-map',
  plugins: [ 
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      inject: true,
    }),
  ],

});

и webpack.base.babel. js:

/* eslint-disable */
/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');
const dotenv = require('dotenv');

const env = {
  NODE_ENV: JSON.stringify(process.env.NODE_ENV),
  REACT_APP_VERSION: JSON.stringify(process.env.REACT_APP_VERSION),
};
const envConfig = dotenv.config({ path: `./.env.${process.env.NODE_ENV}` }).parsed;
for (const k in envConfig) {
  env[k] = envConfig[k];
}

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    rules: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel-loader',
      include: /(app|internals|server)/,
      query: options.babelQuery,
    }, {
      // Do not transform vendor's CSS with CSS-modules
      // The point is that they remain in global scope.
      // Since we require these CSS files in our JS or CSS files,
      // they will be a part of our compilation either way.
      // So, no need for ExtractTextPlugin here.
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
      loader: 'url-loader?limit=10000&mimetype=image/svg+xml',
    }, {
      test: /\.(eot|ttf|woff|woff2)$/,
      loader: 'url-loader?limit=100000',
    }, {
      test: /\.(jpg|png|gif)$/,
      loaders: [
        'file-loader',
        {
          loader: 'image-webpack-loader',
          query: {
            progressive: true,
            optimizationLevel: 7,
            interlaced: false,
            pngquant: {
              quality: '65-90',
              speed: 4,
            },
          },
        },
      ],
    }, {
      test: /\.html$/,
      loader: 'html-loader',
    }, {
      test: /\.(mp4|webm)$/,
      loader: 'url-loader',
      query: {
        limit: 10000,
      },
    }],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': env,
    }),
    //new webpack.NamedModulesPlugin(), //webpack4 does this for us now
    new webpack.IgnorePlugin(/^\.\/lang$/, /moment$/),
  ]),
  resolve: {
    modules: ['app', 'node_modules'],
    mainFields: [
      'browser',
      'jsnext:main',
      'main',
    ],
    alias: {
      moment$: 'moment/moment.js',
    },
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  node: {
    fs: 'empty'
  },
  performance: options.performance || {},
});

Обновление: я обнаружил, что если я установлю --mode=production, то У меня все работает ... и вставляя devtool: 'cheap-module-source-map', я получаю файлы карт - так что я могу делать отладку ... но это не объясняет, почему, когда я устанавливаю режим разработки, ничего не работает ..

prod webpack : вызывается идентично из пакета. json за исключением конфигурационного файла

// Important modules this config uses
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

module.exports = require('./webpack.base.babel')({
  // In production, we skip all hot-reloading stuff
  entry: [
    path.join(process.cwd(), 'app/app.js'),
  ],

  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js',
    publicPath: '/app/',
  },

  plugins: [
    //new webpack.optimize.CommonsChunkPlugin({
    //  name: 'vendor',
    //  children: true,
    //  minChunks: 2,
    //  async: true,
    //}),

    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
    }),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    new OfflinePlugin({
      relativePaths: false,
      publicPath: '/app/',

      // No need to cache .htaccess. See http://mxs.is/googmp,
      // this is applied before any match in `caches` section
      excludes: ['.htaccess'],

      caches: {
        main: [':rest:'],

        // All chunks marked as `additional`, loaded after main section
        // and do not prevent SW to install. Change to `optional` if
        // do not want them to be preloaded at all (cached only when first loaded)
        additional: ['*.chunk.js'],
      },

      // Removes warning for about `additional` section usage
      safeToUseOptionalCaches: true,

      AppCache: false,

      updateStrategy: 'changed',
      autoUpdate: 1000 * 60 * 2,
      externals: ['/'],
      ServiceWorker: {
        events: true,
        navigateFallbackURL: '/',
        publicPath: '/sw.js',
      },
    }),
  ],

  performance: {
    assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)),
  },
});

зависимостей. js

// No need to build the DLL in production
if (process.env.NODE_ENV === 'production') {
  process.exit(0);
} 

require('shelljs/global');

const path = require('path');
const fs = require('fs');
const exists = fs.existsSync;
const writeFile = fs.writeFileSync;

const defaults = require('lodash/defaultsDeep');
const pkg = require(path.join(process.cwd(), 'package.json'));
const config = require('../config');
const dllConfig = defaults(pkg.dllPlugin, config.dllPlugin.defaults);
const outputPath = path.join(process.cwd(), dllConfig.path);
const dllManifestPath = path.join(outputPath, 'package.json');

/**
 * I use node_modules/react-boilerplate-dlls by default just because
 * it isn't going to be version controlled and babel wont try to parse it.
 */
mkdir('-p', outputPath);

echo('Building the Webpack DLL...');

/**
 * Create a manifest so npm install doesn't warn us
 */
if (!exists(dllManifestPath)) {
  writeFile(
    dllManifestPath,
    JSON.stringify(defaults({
      name: 'react-boilerplate-dlls',
      private: true,
      author: pkg.author,
      repository: pkg.repository,
      version: pkg.version,
    }), null, 2),
    'utf8'
  );
}

echo ('Made manifest - building DLL');

// the BUILDING_DLL env var is set to avoid confusing the development environment
exec('cross-env BUILDING_DLL=true webpack --mode=development --display-chunks --color --config internals/webpack/webpack.dll.babel.js');

Конфигурация для зависимостей. js

const resolve = require('path').resolve;
const pullAll = require('lodash/pullAll');
const uniq = require('lodash/uniq');

const ReactBoilerplate = {
  // This refers to the react-boilerplate version this project is based on.
  version: '3.7.0',

  /**
   * The DLL Plugin provides a dramatic speed increase to webpack build and hot module reloading
   * by caching the module metadata for all of our npm dependencies. We enable it by default
   * in development.
   *
   *
   * To disable the DLL Plugin, set this value to false.
   */
  dllPlugin: {
    defaults: {
      /**
       * we need to exclude dependencies which are not intended for the browser
       * by listing them here.
       */
      exclude: [
        'bootstrap-css-only',
        'chalk',
        'compression',
        'cross-env',
        'express',
        'ip',
        'minimist',
        'sanitize.css',
      ],

      /**
       * Specify any additional dependencies here. We include core-js and lodash
       * since a lot of our dependencies depend on them and they get picked up by webpack.
       */
      include: ['core-js', 'lodash'],
      //'eventsource-polyfill', 'babel-polyfill', - removed since core-js 'usage' now handles this

      // The path where the DLL manifest and bundle will get built
      path: resolve('../node_modules/react-boilerplate-dlls'),
    },

    entry(pkg) {
      const dependencyNames = Object.keys(pkg.dependencies);
      const exclude = pkg.dllPlugin.exclude || ReactBoilerplate.dllPlugin.defaults.exclude;
      const include = pkg.dllPlugin.include || ReactBoilerplate.dllPlugin.defaults.include;
      const includeDependencies = uniq(dependencyNames.concat(include));

      return {
        reactBoilerplateDeps: pullAll(includeDependencies, exclude),
      };
    },
  },
};

module.exports = ReactBoilerplate;
...