roadhog迁移成webpack4问题整理

[webpack-cli] Error: Cannot find module 'object.getownpropertydescriptors'

可能是webpack-cli版本的问题,我的项目是从3.1.1升级到4.9.1好了。  

0 info it worked if it ends with ok1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle [email protected]~prestart: [email protected]
6 info lifecycle [email protected]~start: [email protected]
7 verbose lifecycle [email protected]~start: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~start: PATH: C:\Users\yangsmc\AppData\Roaming\nvm\v12.22.0\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\yt-program\自助webpack4\node_modules\.bin;C:\Users\liuzhana\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\liuzhana\bin;C:\Program Files (x86)\NetSarang\Xftp 6;C:\Program Files (x86)\NetSarang\Xshell 6;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\Citrix\System32;C:\Program Files\Citrix\ICAService;C:\Program Files\TortoiseSVN\bin;C:\Users\yangsmc\AppData\Roaming\nvm;C:\Program Files\nodejs;C:\Program Files\Git\cmd;C:\Program Files (x86)\Yarn\bin;C:\Users\liuzhana\AppData\Roaming\npm;C:\Users\liuzhana\AppData\Local\Yarn\bin;C:\Program Files\nodejs;C:\Users\liuzhana\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\liuzhana\AppData\Local\Yarn\bin;C:\Users\yangsmc\AppData\Roaming\nvm;C:\Program Files\nodejs;C:\Users\liuzhana\AppData\Roaming\npm;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl
9 verbose lifecycle [email protected]~start: CWD: C:\yt-program\自助webpack4
10 silly lifecycle [email protected]~start: Args: [
10 silly lifecycle   '/d /s /c',
10 silly lifecycle   'webpack-dev-server --config=webpack.config.development.js --mode development'
10 silly lifecycle ]
11 silly lifecycle [email protected]~start: Returned: code: 2  signal: null
12 info lifecycle [email protected]~start: Failed to exec start script
13 verbose stack Error: [email protected] start: `webpack-dev-server --config=webpack.config.development.js --mode development`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter. (C:\Users\yangsmc\AppData\Roaming\nvm\v12.22.0\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:314:20)
13 verbose stack     at ChildProcess. (C:\Users\yangsmc\AppData\Roaming\nvm\v12.22.0\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:314:20)
13 verbose stack     at maybeClose (internal/child_process.js:1022:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5)
14 verbose pkgid [email protected]
15 verbose cwd C:\yt-program\自助webpack4
16 verbose Windows_NT 6.1.7601
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.22.7
19 verbose npm  v6.14.15
20 error code ELIFECYCLE
21 error errno 2
22 error [email protected] start: `webpack-dev-server --config=webpack.config.development.js --mode development`
22 error Exit status 2
23 error Failed at the [email protected] start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

 忘记解决方式了

[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'contentBase'. These properties are valid:
   object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }

 webpack-cli这个版本devServer中没有这个contentBase属性。

 devServer: {
    // contentBase: resolve(__dirname, "build"),
    static:resolve(__dirname, "build"),
  }

./src/index.js
Module build failed (from ./node_modules/[email protected]@babel-loader/lib/index.js):
Error: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.

 babel-loader版本高8.2.5降为8.0.0,.babelrc.js文件presets中加入@babel/preset-env

/src/routes/Contract/ContractFile/file.pdf 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

 忘记配置pdf文件规则,{ test: /\.pdf$/i, use: 'file-loader', },

./src/routes/Attendance/vacationDetail/index.less
Module build failed (from ./node_modules/[email protected]@mini-css-extract-plugin/dist/loader.js):
ModuleNotFoundError: Module not found: Error: Can't resolve './@/assets/font/UnidreamLED.ttf' in 'C:\yt-program\自助webpack4\src\routes\Attendance\vacationDetail'

 mini-css-extract-plugin版本低

chunk styles [mini-css-extract-plugin]
Conflicting order between:
 * css ./node_modules/[email protected]@css-loader/dist/cjs.js??ref--7-1!./node_modules/[email protected]@less-loader/dist/cjs.js??ref--7-2!./src/components/MultipleLov/index.less
 * css ./node_modules/[email protected]@css-loader/dist/cjs.js??ref--7-1!./node_modules/[email protected]@less-loader/dist/cjs.js??ref--7-

 项目中引入相同css样式的组件,引入顺序不一致。需要在mini-css-extract-plugin加入ignoreOrder:true。具体含义参考mini-css-extract-plugin - npm

[webpack-cli] TypeError: Invalid value used in weak set
    at WeakSet.add ()
    at MiniCssExtractPlugin.apply (C:\yt-program\自助webpack4\node_modules\[email protected]@mini-css-extract-plugin\dist\index.js:640:18)
    at WebpackCLI.webpack (C:\yt-program\自助webpack4\node_modules\[email protected]@webpack\lib\webpack.js:51:13)
    at WebpackCLI.createCompiler (C:\yt-program\自助webpack4\node_modules\[email protected]@webpack-cli\lib\webpack-cli.js:2193:23)
    at async Command. (C:\yt-program\自助webpack4\node_modules\_@[email protected]@@webpack-cli\serve\lib\index.js:106:30)
    at async Promise.all (index 1)
    at async Command. (C:\yt-program\自助webpack4\node_modules\[email protected]@webpack-cli\lib\webpack-cli.js:1674:7)

 mini-css-extract-plugin依赖版本有问题我最终用的时0.9.0

Module build failed (from ./node_modules/[email protected]@mini-css-extract-plugin/dist/loader.js):
ValidationError: Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'modifyVars'. These properties are valid:
   object { publicPath?, esModule?, modules? }
    at validate (C:\yt-program\自助webpack4\node_modules\[email protected]@schema-utils\dist\validate.js:105:11)
    at Object.pitch (C:\yt-program\自助webpack4\node_modules\[email protected]@mini-css-extract-plugin\dist\loader.js:53:29)

 mini-css-extract-plugin依赖这个版本没有modifyVars这个属性,看过版本说明之后才知道高版本移除这个属性了,1.3.6降为0.9.0,成功解决。

pre-commit:
pre-commit: We've failed to pass the specified git pre-commit hooks as the `precommit`
pre-commit: hook returned an exit code (1). If you're feeling adventurous you can
pre-commit: skip the git pre-commit hooks by adding the following flags to your commit:
pre-commit:
pre-commit:   git commit -n (or --no-verify)
pre-commit:
pre-commit: This is ill-advised since the commit is broken.

 代码规范检测不过,删除根目录下.git/hooks的pre-commit文件。

ERROR in ./node_modules/[email protected]@slick-carousel/slick/slick-theme.css
Module build failed (from ./node_modules/[email protected]@mini-css-extract-plugin/dist/loader.js):
ModuleParseError: Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
    at handleParseError (C:\yt-program\自助webpack4\node_modules\[email protected]@webpack\lib\NormalModule.js:469:19)
    at C:\yt-program\自助webpack4\node_modules\[email protected]@webpack\lib\NormalModule.js:503:5
    at C:\yt-program\自助webpack4\node_modules\[email protected]@webpack\lib\NormalModule.js:358:12
    at C:\yt-program\自助webpack4\node_modules\[email protected]@loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (C:\yt-program\自助webpack4\node_modules\[email protected]@loader-runner\lib\LoaderRunner.js:214:10)
    at Array. (C:\yt-program\自助webpack4\node_modules\[email protected]@loader-runner\lib\LoaderRunner.js:205:4)
    at Storage.finished (C:\yt-program\自助webpack4\node_modules\[email protected]@enhanced-resolve\lib\CachedInputFileSystem.js:55:16)
    at C:\yt-program\自助webpack4\node_modules\[email protected]@enhanced-resolve\lib\CachedInputFileSystem.js:91:9
    at C:\yt-program\自助webpack4\node_modules\[email protected]@graceful-fs\graceful-fs.js:123:16
    at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
 @ ./src/routes/Vacation/VacationCharts.js 50:0-46
 @ ./src/routes/Vacation/MyVacation.js
 @ ./src/common/router.js
 @ ./src/router.js
 @ ./src/index.js


webpack.config.production.js中rules的css配置不对,改为

{ test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { importLoaders: 1, }, }, 'postcss-loader', ], },
Unhandled promise rejection Error: Loading chunk 144 failed.

页面白屏

 webpack.config.production.js中的output.publicPath:'./'改为’/‘,就好了。

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\yt-
program\自助webpack4\node_modules\[email protected]@chalk\source\index.js
require() of ES modules is not supported.
require() of C:\yt-program\自助webpack4\node_modules\[email protected]@chalk\source\i
ndex.js from C:\yt-program\自助webpack4\webpack.config.production.js is an ES mo
dule file as it is a .js file whose nearest parent package.json contains "type":
 "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(
), or remove "type": "module" from C:\yt-program\自助webpack4\node_modules\_chal
[email protected]@chalk\package.json.

chalk依赖版本过高,造成es6无法解析, 5.0.1降到4.0.0,成功修复问题。

发到服务器,点开部分页面,控制台报React is not defined

因为部分组件缺少了react依赖,可以在webpack.config.js的plugins配置插件

new webpack.ProvidePlugin({ // 根据上下文,在需要依赖React处,自动引入
    "React": "react",
})
@connect装饰器报错

HOC 的装饰器写法,需要配置 babel 支持。现在 webpack 一般都不直接在自身配置文件里面设置 babel 了,而是将 babel 的配置信息抽出来放到.babelrc内以 JSON 格式维护,在plugins内加入下面这段即可:

["@babel/plugin-proposal-decorators", { "legacy": true }],

最后的配置文件

package.json

{
  "name": "boogoohr",
  "version": "3.0.0",
  "description": "An out-of-box UI solution for enterprise applications",
  "private": true,
  "scripts": {
    "start": "webpack-dev-server --config=webpack.config.development.js --mode development",
    "build": "cross-env NODE_ENV=production webpack --config=webpack.config.production.js --mode production",
    "webpack": "webpack --version"
  },
  "dependencies": {
    "@antv/data-set": "^0.8.0",
    "@babel/polyfill": "^7.0.0-beta.36",
    "@babel/runtime-corejs2": "^7.0.0",
    "@balkangraph/orgchart.js": "^7.1.2",
    "antd": "^3.14.0",
    "axios": "^0.18.0",
    "bizcharts": "^3.1.10",
    "bizcharts-plugin-slider": "^2.0.1",
    "classnames": "^2.2.5",
    "dragm": "0.0.5",
    "dva": "^2.2.3",
    "dva-loading": "^2.0.3",
    "echarts": "^4.2.0-rc.2",
    "enquire-js": "^0.2.1",
    "event-emitter": "^0.3.5",
    "history": "^4.10.1",
    "jsencrypt": "^3.0.0-rc.1",
    "lodash": "^4.17.10",
    "lodash-decorators": "^6.0.0",
    "moment": "^2.19.3",
    "number-precision": "^1.5.2",
    "numeral": "^2.0.6",
    "omit.js": "^1.0.0",
    "path-to-regexp": "^2.1.0",
    "postcss-loader": "^4.0.0",
    "prop-types": "^15.5.10",
    "qrcode.react": "^1.0.0",
    "qs": "^6.5.0",
    "querystring": "^0.2.0",
    "rc-calendar": "^9.7.4",
    "rc-drawer": "^1.2.0",
    "react": "16.14.0",
    "react-addons-pure-render-mixin": "^15.6.2",
    "react-color": "^2.14.1",
    "react-container-query": "^0.11.0",
    "react-countup": "^4.3.3",
    "react-cropper": "^1.0.1",
    "react-document-title": "^2.0.3",
    "react-dom": "^16.4.1",
    "react-draggable-tags": "^1.0.6",
    "react-fittext": "^1.0.0",
    "react-intl": "^2.4.0",
    "react-intl-universal": "^1.12.1",
    "react-pdf": "^3.0.5",
    "react-router-piwik": "^0.0.4",
    "react-slick": "^0.23.2",
    "react-watermark-module": "^1.2.0",
    "react.eval": "^1.4.14",
    "rollbar": "^2.3.4",
    "screenfull": "^3.3.2",
    "setprototypeof": "^1.1.0",
    "slick-carousel": "^1.8.1",
    "sockjs-client": "^1.6.1",
    "thread-loader": "^3.0.4",
    "url-polyfill": "^1.0.10",
    "uuid": "^8.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/plugin-proposal-decorators": "^7.0.0",
    "@babel/plugin-proposal-do-expressions": "^7.0.0",
    "@babel/plugin-proposal-export-default-from": "^7.0.0",
    "@babel/plugin-proposal-export-namespace-from": "^7.0.0",
    "@babel/plugin-proposal-function-bind": "^7.0.0",
    "@babel/plugin-proposal-function-sent": "^7.0.0",
    "@babel/plugin-proposal-json-strings": "^7.0.0",
    "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0",
    "@babel/plugin-proposal-numeric-separator": "^7.0.0",
    "@babel/plugin-proposal-optional-chaining": "^7.0.0",
    "@babel/plugin-proposal-pipeline-operator": "^7.0.0",
    "@babel/plugin-proposal-throw-expressions": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/plugin-syntax-import-meta": "^7.0.0",
    "@babel/plugin-transform-runtime": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "@nodelib/fs.scandir": "^2.1.5",
    "@nodelib/fs.walk": "^1.2.8",
    "@webassemblyjs/ast": "^1.3.1",
    "@webassemblyjs/wasm-edit": "^1.3.1",
    "acorn": "^6.1.1",
    "add-asset-html-webpack-plugin": "^3.1.3",
    "address": "^1.0.3",
    "antd-theme-generator": "^1.2.11",
    "antd-theme-webpack-plugin": "1.1.5",
    "atool-build": "^0.9.3",
    "atool-test-mocha": "^0.1.4",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^8.0.0",
    "babel-plugin-dva-hmr": "^0.4.1",
    "babel-plugin-import": "^1.7.0",
    "babel-plugin-module-resolver": "^3.1.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-remove-console": "^6.9.2",
    "babel-plugin-transform-runtime": "^6.8.0",
    "babel-runtime": "^6.9.2",
    "body-parser": "^1.18.3",
    "chalk": "^4.0.0",
    "clean-webpack-plugin": "^0.1.19",
    "copy-webpack-plugin": "^4.5.1",
    "cross-env": "^5.1.1",
    "cross-port-killer": "^1.0.1",
    "css-loader": "^2.1.1",
    "cssnano": "^4.1.10",
    "dora": "0.4.x",
    "dora-plugin-webpack": "^0.8.1",
    "enzyme": "^3.1.0",
    "es5-imcompatible-versions": "^0.1.34",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-prettier": "^2.9.0",
    "eslint-plugin-babel": "^5.1.0",
    "eslint-plugin-compat": "^2.2.0",
    "eslint-plugin-import": "^2.17.3",
    "eslint-plugin-jsx-a11y": "^6.0.3",
    "eslint-plugin-markdown": "^1.0.0-beta.6",
    "eslint-plugin-react": "^7.7.0",
    "estraverse": "^4.2.0",
    "expect": "^1.20.2",
    "fastq": "^1.13.0",
    "file-loader": "^1.1.11",
    "filemanager-webpack-plugin": "^7.0.0",
    "friendly-errors-webpack-plugin": "^1.7.0",
    "gh-pages": "^1.0.0",
    "happypack": "^5.0.0-beta.4",
    "html-webpack-plugin": "^4.5.0",
    "husky": "^8.0.1",
    "keymaster": "^1.6.2",
    "less": "^3.0.4",
    "less-loader": "^4.1.0",
    "lint-staged": "^7.2.0",
    "mini-css-extract-plugin": "^0.9.0",
    "mockjs": "^1.0.1-beta3",
    "open-browser-webpack-plugin": "0.0.5",
    "optimize-css-assets-webpack-plugin": "^5.0.1",
    "pre-commit": "^1.2.2",
    "prettier": "1.13.5",
    "pro-download": "^1.0.1",
    "progress-bar-webpack-plugin": "^1.12.1",
    "react-loadable": "^5.4.0",
    "react-pdf-js": "^4.0.0-alpha.6",
    "redbox-react": "^1.5.0",
    "redux-devtools": "^3.4.1",
    "redux-devtools-dock-monitor": "^1.1.3",
    "redux-devtools-log-monitor": "^1.4.0",
    "regenerator-runtime": "^0.12.0",
    "sass-loader": "^7.0.1",
    "serve-index": "^1.9.1",
    "speed-measure-webpack-plugin": "^1.5.0",
    "string-replace-loader": "^2.1.1",
    "style-loader": "^2.0.0",
    "stylelint": "^9.2.1",
    "stylelint-config-prettier": "^3.0.4",
    "stylelint-config-standard": "^18.0.0",
    "type-is": "^1.6.15",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "url-loader": "^1.0.1",
    "webpack": "^4.33.0",
    "webpack-bundle-analyzer": "^4.5.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.9.2",
    "webpack-manifest-plugin": "^2.0.4"
  },
  "optionalDependencies": {
    "puppeteer": "^1.4.0"
  },
  "pre-commit": [
    "precommit"
  ],
  "lint-staged": {
    "**/*.{js,jsx,less}": [
      "prettier --write",
      "git add"
    ],
    "**/*.{js,jsx}": "npm run lint-staged:js",
    "**/*.less": "stylelint --syntax less"
  },
  "engines": {
    "node": ">=8.0.0"
  },
  "jest": {
    "verbose": true,
    "testURL": "http://localhost"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 10"
  ],
  "entry": {
    "index": "src/index.ejs"
  }
}

webpack.config.development.js

/* eslint-disable */
const webpack = require("webpack");
const path = require("path");
const chalk = require("chalk");
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");
var ManifestPlugin = require("webpack-manifest-plugin");
const theme = require("./src/theme");
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
var FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');


module.exports = {
  entry: path.resolve(__dirname, "src", "index.js"),
  devServer: {
    // contentBase: path.resolve(__dirname, 'dist'),
    host: "0.0.0.0",
    port: 8080,
    open: false,
    hot: true,
    // quiet: true,
    historyApiFallback: true,
    // overlay: {
    //   errors: true
    // },
    // stats: {
    //   children: false,
    //   chunks: false,
    //   assets: false,
    //   modules: false
    // },
    proxy: {
        
      },
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    publicPath: "/",
    chunkFilename: "[name].async.js",
    library: "[name]_dll"
  },
  resolve: {
    alias: {
      components: path.resolve(__dirname, 'src/components/'),
      assets: path.resolve(__dirname, 'src/assets/'),
      '@': path.resolve(__dirname, 'src'),
      'uuid/v4': path.resolve(__dirname, 'src/utils/uuid_v4.js'),
      '@services': path.resolve(__dirname, 'src/services'),
    }
  },
  module: {
    rules: [
      {
        test: /\.pdf$/i,
        use: 'file-loader',
      },
      {
        test: /\.js$/,
        include: [path.resolve(__dirname, "src")],
        exclude: [],
        loader: "babel-loader?cacheDirectory",
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: "css-loader",
            options: {
              importLoaders: 1
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: true,
                // if hmr does not work, this is a forceful method.
              reloadAll: true,
              modifyVars: theme
            },
          },
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
              importLoaders: 1,
              modules: true,
              localIdentName: "[name]_[local]-[hash:base64:5]"
            }
          },
          {
            loader: "less-loader",
            options: {
              sourceMap: true,
              javascriptEnabled: true,
              modifyVars: theme
            }
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          // { //css热更新失败
          //   loader: MiniCssExtractPlugin.loader,
          //   options: {
          //     hmr: process.env.NODE_ENV === 'development',
          //     roloadAll: true
          //   }
          // },
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
              importLoaders: 1
            }
          },
          {
            loader: "less-loader",
            options: {
              sourceMap: true,
              javascriptEnabled: true,
              modifyVars: theme
            }
          }
        ],
        exclude: /src/
      },
      {
        test: /\.(ttf|eot|svg|woff|woff2|png|svg|jpg|gif)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  },
  externals: {
    jquery: "jQuery"
  },
  node: {
    fs: "empty",
    module: "empty"
  },
  devtool: "source-map",
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: "styles",
          test: /\.(css|less)/,
          chunks: "all",
          enforce: true
        }
      }
    }
  },
  plugins: [
    new OpenBrowserPlugin({url: 'http://localhost:8080/'}),
    new ProgressBarPlugin(
      {
        width: 50, // 默认20,进度格⼦数量即每个代表进度数,如果是20,那么⼀格就是5。
        format: `${chalk.blue.bold("build") + chalk.yellow('[:bar] ') + chalk.green.bold(':percent') } (:elapsed秒)`,
        stream: process.stderr, // 默认stderr,输出流
        complete: "#", // 默认“=”,完成字符
        clear: false, // 默认true,完成时清除栏的选项
        renderThrottle: "", // 默认16,更新之间的最短时间(以毫秒为单位)
        callback() { // 进度条完成时调⽤的可选函数
          console.log(chalk.red.bold("完成"));
        },
      }
    ),
    new FriendlyErrorsWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      ignoreOrder: true,
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "src", "index.ejs"),
      filename: "index.html",
      hash: true
    }),
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, "public")
      }
    ]),
    new webpack.HotModuleReplacementPlugin(),
    new ManifestPlugin(),
    new webpack.ProvidePlugin({ // React is not defined, 在需要的地方自动引入
      'React': 'react',
    }),
  ]
};

webpack.config.production.js

const webpack = require('webpack');
const path = require('path');
const chalk = require("chalk");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HappyPack = require('happypack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
const os = require('os');

const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });

const theme = require('./src/theme');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: '[name].[chunkhash:8].js',
    path: path.resolve(__dirname, 'dist/dist'),
    publicPath: '/',
    chunkFilename: '[name].[chunkhash:8].async.js',
  },

  resolve: {
    alias: {
        components: path.resolve(__dirname, 'src/components/'),
        assets: path.resolve(__dirname, 'src/assets/'),
        '@': path.resolve(__dirname, 'src/'),
        'uuid/v4': path.resolve(__dirname, 'src/utils/uuid_v4.js'),
        '@services': path.resolve(__dirname, 'src/services'),
    },
  },

  module: {
    rules: [
      {
        test: /\.pdf$/i,
        use: 'file-loader',
      },
      {
        test: /\.js$/,
        include: [path.resolve(__dirname, 'src')],
        use: ['happypack/loader?id=babel'],
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
            },
          },
          'postcss-loader',
        ],
      },
      {
        test: /\.(less)$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[name]_[local]-[hash:base64:5]',
            },
          },
          'postcss-loader',
          {
            loader: 'less-loader',
            options: {
              javascriptEnabled: true,
              modifyVars: theme,
            },
          },
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
            },
          },
          'postcss-loader',
          {
            loader: 'less-loader',
            options: {
              javascriptEnabled: true,
              modifyVars: theme,
            },
          },
        ],
        exclude: /src/,
      },
      {
        test: /\.(ttf|eot|svg|woff|woff2|png|svg|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
              outputPath: './assets/',
            },
          },
        ],
      },
    ],
  },
  stats: {
    children: false,
    warningsFilter: warn => warn.indexOf('Conflicting order between:') > -1,
  },
  node: {
    fs: 'empty',
    module: 'empty',
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.(css|less)/,
          chunks: 'all',
          enforce: true,
        },
        commons: {
          name: 'commons',
          chunks: 'initial',
          minChunks: 2,
        },
        vendors: {
          name: 'vendors',
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
        },
      },
    },
    runtimeChunk: true,
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      ignoreOrder: true,
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'src', 'index.ejs'), // 模板
      filename: 'index.html',
      hash: true,
      showErrors: true,
      minify: false,
    }),
    new ProgressBarPlugin({
      width: 50, // 默认20,进度格⼦数量即每个代表进度数,如果是20,那么⼀格就是5。
      format: `${chalk.blue.bold("build") + chalk.yellow('[:bar] ') + chalk.green.bold(':percent') } (:elapsed秒)`,
      stream: process.stderr, // 默认stderr,输出流
      complete: "#", // 默认“=”,完成字符
      clear: false, // 默认true,完成时清除栏的选项
      renderThrottle: "", // 默认16,更新之间的最短时间(以毫秒为单位)
      callback() { // 进度条完成时调⽤的可选函数
        console.log(chalk.red.bold("完成"));
      },
    }),
    new CleanWebpackPlugin(["dist", "dist.zip"]),
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, 'public'),
        ignore: ['config.js'],
      },
    ]),
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: require('cssnano'),
      cssProcessorOptions: { discardComments: { removeAll: true } },
      canPrint: true,
    }),
    new HappyPack({
      id: 'babel',
      loaders: ['babel-loader?cacheDirectory'],
      threadPool: happyThreadPool,
    }),
    new webpack.HashedModuleIdsPlugin(),
    new webpack.ProvidePlugin({ // React is not defined, 在需要的地方自动引入
      'React': 'react',
    }),
    new FileManagerPlugin({
      events: {
        onEnd: {
          archive: [{ source: 'dist', destination: 'dist.zip'}],
        },
      },
    }),
  ],
};

你可能感兴趣的:(React,webpack,vue.js,javascript,前端)