Webpack создает отдельные файлы JS для нескольких импортов - PullRequest
0 голосов
/ 27 октября 2019

Я пытаюсь создать пользовательскую конфигурацию веб-пакета для сложного проекта. При сборке я заметил, что при импорте babel-runtime/core-js/json/stringify веб-пакет генерирует отдельный файл JS. Может кто-нибудь помочь мне понять, что здесь происходит и почему webpack генерирует отдельный файл JS.

package.json

{
  "name": "react-boilerplate",
  "version": "1.0.0",
  "description": "A boilerplate for large scale react apps",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "webpack-dev-server --mode development",
    "build": "sh -ac 'webpack --mode production ${DEPLOY_TARGET:+--env.target $DEPLOY_TARGET}'",
    "build:production": "DEPLOY_TARGET='production' yarn build",
    "build:staging": "DEPLOY_TARGET='staging' yarn build"
  },
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/preset-env": "^7.6.3",
    "@babel/preset-react": "^7.6.3",
    "@typescript-eslint/eslint-plugin": "2.x",
    "@typescript-eslint/parser": "2.x",
    "babel-eslint": "10.x",
    "babel-loader": "^8.0.6",
    "babel-preset-react-app": "^9.0.2",
    "clean-webpack-plugin": "^3.0.0",
    "compression-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^5.0.4",
    "dotenv": "^8.2.0",
    "eslint": "6.x",
    "eslint-config-react-app": "^5.0.2",
    "eslint-loader": "^3.0.2",
    "eslint-plugin-flowtype": "3.x",
    "eslint-plugin-import": "2.x",
    "eslint-plugin-jsx-a11y": "6.x",
    "eslint-plugin-react": "7.x",
    "eslint-plugin-react-hooks": "1.x",
    "file-loader": "^4.2.0",
    "html-webpack-plugin": "^3.2.0",
    "react-hot-loader": "^4.12.15",
    "stylelint": "^11.1.1",
    "stylelint-config-standard": "^19.0.0",
    "stylelint-config-styled-components": "^0.1.1",
    "stylelint-custom-processor-loader": "^0.6.0",
    "stylelint-processor-styled-components": "^1.8.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9",
    "webpack-dev-server": "^3.8.2",
    "webpack-merge": "^4.2.2",
    "workbox-webpack-plugin": "^4.3.1"
  },
  "dependencies": {
    "lodash": "^4.17.15",
    "react": "^16.10.2",
    "react-dom": "^16.10.2",
    "react-router-dom": "^5.1.2",
  },
  "peerDependencies": {
    "stylelint": "^11.1.1"
  }
}

webpack.config.js

const { DefinePlugin } = require('webpack');
const path = require('path');

// Webpack plugins
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWepackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const { rootDir } = require('./utils');

const {
  entryPath,
  getEnvJson,
  htmlTemplatePath,
  outputDir,
  publicDir,
  sourceDir,
} = require('./utils');

module.exports = env => ({
  // Configure's our app entry points
  entry: {
    main: entryPath,
  },

  // Configure's loaders to let webpact know how different extension should be
  // loaded when bundling
  module: {
    rules: [
      // Configure's babel loader for transpiling javascript, eslint loader
      // for linting javascript, stylelint loader for css linting
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [
          'babel-loader',
          {
            loader: 'stylelint-custom-processor-loader',
            options: {
              configPath: path.resolve(rootDir, '.stylelintrc.js'),
            },
          },
          'eslint-loader',
        ]
      },

      // Configure's loaders for images
      {
        test: /.(png|jpg|jpeg|svg|gif)/,
        use: 'file-loader'
      },
    ]
  },

  // Configure's destination for the bundled code
  output: {
    path: outputDir,
  },

  // Configure's additions plugins to be used by webpack
  // Order of plugins is important
  plugins: [
    // Removes all the contents of output folder(but not the folder itself)
    // before every webpack build
    new CleanWebpackPlugin(),

    // Copies all contents of public folder as it is excluding index.html file
    new CopyWepackPlugin([
      {
        from: publicDir,
        to: outputDir,
        ignore: ['index.html']
      }
    ]),

    // Injects target specific enviroment variables
    new DefinePlugin({
      'process.env': getEnvJson(env.target)
    }),

    // Uses `public/index.html` and creates a `index.html` file for the app
    // by injecting the generated bundles javascript files
    new HtmlWebpackPlugin({
      template: htmlTemplatePath
    }),
  ],

  // Configure's custom behavior for how modules are resolved by webpack
  resolve: {
    modules: [sourceDir, 'node_modules']
  }
});

.babelrc

{
  "presets": ["react-app"]
}

Ответы [ 2 ]

0 голосов
/ 27 октября 2019

Проблема с регулярным выражением загрузчика файлов, которое было неправильно настроено и привело к совпадению babel-runtime/core-js/json/stringify. Поэтому для его загрузки использовался загрузчик файлов.

0 голосов
/ 27 октября 2019

Это из-за вашего entryPath.

module.exports = {
  entry: {
    bundle1: '.src/fileForBundle1.js',
    bundle2: '.src/fileForBundle2.js'
  },

Это приведет к созданию двух пакетов.

Убедитесь, что entryPath не является объектом с несколькими значениями.

...