@Alex_87

Не работает webpack.config?

Здравствуйте! На просторах интернета нашёл файл с webpack.config и package.json . После установки node_modules, запустил команду npm run dev, которая выдала мне следующую ошибку:

CopyPlugin Invalid Options

options should be array

ValidationError: CopyPlugin Invalid Options
at validateOptions (C:\Users\Admin\Desktop\webpack-2020-master\node_modules\schema-utils\src\validateOptions.js:32:11)
at new CopyPlugin (C:\Users\Admin\Desktop\webpack-2020-master\node_modules\copy-webpack-plugin\dist\index.js:26:30)
at plugins (C:\Users\Admin\Desktop\webpack-2020-master\webpack.config.js:91:5)
at Object. (C:\Users\Admin\Desktop\webpack-2020-master\webpack.config.js:135:12)
at Module._compile (C:\Users\Admin\Desktop\webpack-2020-master\node_modules\v8-compile-cache\v8-compile-cache.js:192:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (C:\Users\Admin\Desktop\webpack-2020-master\node_modules\v8-compile-cache\v8-compile-cache.js:161:20)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webpack-course-2020@1.0.0 dev: `cross-env NODE_ENV=development webpack --mode development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the webpack-course-2020@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2020-10-19T06_56_36_666Z-debug.log

Помогите пожалуйста разобраться, что не так

Файл package.json

{
  "name": "webpack-course-2020",
  "version": "1.0.0",
  "description": "webpack course",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack --mode development",
    "build": "cross-env NODE_ENV=production webpack --mode production",
    "watch": "cross-env NODE_ENV=development webpack --mode development --watch",
    "start": "cross-env NODE_ENV=development webpack-dev-server --mode development --open",
    "stats": "webpack --json > stats.json && webpack-bundle-analyzer stats.json"
  },
  "browserslist": "> 0.25%, not dead",
  "keywords": [
    "js",
    "javascript",
    "webpack"
  ],
  "author": "Vladilen <v@mail.ru>",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.8.3",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/preset-env": "^7.8.3",
    "@babel/preset-react": "^7.8.3",
    "@babel/preset-typescript": "^7.8.3",
    "babel-eslint": "^10.0.3",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^5.1.1",
    "cross-env": "^6.0.3",
    "css-loader": "^3.4.2",
    "csv-loader": "^3.0.2",
    "eslint": "^6.8.0",
    "eslint-loader": "^3.0.3",
    "file-loader": "^5.0.2",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "mini-css-extract-plugin": "^0.9.0",
    "node-sass": "^4.13.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "papaparse": "^5.1.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.2",
    "terser-webpack-plugin": "^2.3.2",
    "webpack": "^4.41.5",
    "webpack-bundle-analyzer": "^3.6.0",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.1",
    "xml-loader": "^1.2.1"
  },
  "dependencies": {
    "@babel/polyfill": "^7.8.3",
    "jquery": "^3.4.1",
    "lodash": "^4.17.15",
    "normalize.css": "^8.0.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  }
}


Файл webpack.config
const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const TerserWebpackPlugin = require('terser-webpack-plugin')
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer')

const isDev = process.env.NODE_ENV === 'development'
const isProd = !isDev

const optimization = () => {
  const config = {
    splitChunks: {
      chunks: 'all'
    }
  }

  if (isProd) {
    config.minimizer = [
      new OptimizeCssAssetWebpackPlugin(),
      new TerserWebpackPlugin()
    ]
  }

  return config
}

const filename = ext => isDev ? `[name].${ext}` : `[name].[hash].${ext}`

const cssLoaders = extra => {
  const loaders = [
    {
      loader: MiniCssExtractPlugin.loader,
      options: {
        hmr: isDev,
        reloadAll: true
      },
    },
    'css-loader'
  ]

  if (extra) {
    loaders.push(extra)
  }

  return loaders
}

const babelOptions = preset => {
  const opts = {
    presets: [
      '@babel/preset-env'
    ],
    plugins: [
      '@babel/plugin-proposal-class-properties'
    ]
  }

  if (preset) {
    opts.presets.push(preset)
  }

  return opts
}


const jsLoaders = () => {
  const loaders = [{
    loader: 'babel-loader',
    options: babelOptions()
  }]

  if (isDev) {
    loaders.push('eslint-loader')
  }

  return loaders
}

const plugins = () => {
  const base = [
    new HTMLWebpackPlugin({
      template: './index.html',
      minify: {
        collapseWhitespace: isProd
      }
    }),
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, 'src/favicon.ico'),
          to: path.resolve(__dirname, 'dist')
        }
      ]
    }),
    new MiniCssExtractPlugin({
      filename: filename('css')
    })
  ]

  if (isProd) {
    base.push(new BundleAnalyzerPlugin())
  }

  return base
}

module.exports = {
  context: path.resolve(__dirname, 'src'),
  mode: 'development',
  entry: {
    main: ['@babel/polyfill', './index.jsx'],
    analytics: './analytics.ts'
  },
  output: {
    filename: filename('js'),
    path: path.resolve(__dirname, 'dist')
  },
  resolve: {
    extensions: ['.js', '.json', '.png'],
    alias: {
      '@models': path.resolve(__dirname, 'src/models'),
      '@': path.resolve(__dirname, 'src'),
    }
  },
  optimization: optimization(),
  devServer: {
    port: 4200,
    hot: isDev
  },
  devtool: isDev ? 'source-map' : '',
  plugins: plugins(),
  module: {
    rules: [
      {
        test: /\.css$/,
        use: cssLoaders()
      },
      {
        test: /\.less$/,
        use: cssLoaders('less-loader')
      },
      {
        test: /\.s[ac]ss$/,
        use: cssLoaders('sass-loader')
      },
      {
        test: /\.(png|jpg|svg|gif)$/,
        use: ['file-loader']
      },
      {
        test: /\.(ttf|woff|woff2|eot)$/,
        use: ['file-loader']
      },
      {
        test: /\.xml$/,
        use: ['xml-loader']
      },
      {
        test: /\.csv$/,
        use: ['csv-loader']
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: jsLoaders()
      },
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        loader: {
          loader: 'babel-loader',
          options: babelOptions('@babel/preset-typescript')
        }
      },
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        loader: {
          loader: 'babel-loader',
          options: babelOptions('@babel/preset-react')
        }
      }
    ]
  }
}
  • Вопрос задан
  • 1701 просмотр
Решения вопроса 1
approximate_solution
@approximate_solution
JS Developer. Angular\React\Vue\Ember
CopyPlugin Invalid Options

Тут написано что неправильно задан параметр опций.

options should be array

А здесь ниже для вас написано что опции должны быть переданы как массив с объектами, а не как объекты разделенные. Следовательно нужно сделать массив объектов.

А тут решение для особо одаренных -
https://github.com/webpack-contrib/copy-webpack-pl...

Error Code =
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: 'source', to: 'dest' },
        { from: 'other', to: 'public' },
      ],
    }),
  ],
};


Good Code Example -
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  plugins: [
        new CopyPlugin(
            [
                { from: 'source', to: 'dest' },
                { from: 'other', to: 'public' },
            ]
        ),
  ],
};
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы