1

我最近从 webpack 3 迁移到 5 并根据建议进行了一些更改,但是在此升级后,构建失败并且服务器无法启动。这是我的 webpack 文件


const path = require('path')
const webpack = require('webpack')
const glob = require('glob')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const FileManagerPlugin = require('filemanager-webpack-plugin')

const libraryBaseStyles = glob.sync('./library/basics/**/styles.scss')
const libraryAllStyles = glob.sync('./library/**/styles.scss', {
  ignore: ['./library/basics/**/styles.scss'],
})

const isProd = process.env.NODE_ENV === 'production'

let externals = []
let rules = []
let entries = {}
let pluginsBabel = ['transform-runtime', 'lodash']
let plugins = [
  new ExtractTextPlugin({
    // define where to save the file
    filename: 'css/[name].css',
    allChunks: true,
  }),
]
let output = {
  path: path.resolve(__dirname, isProd ? './dist' : './public'),
  filename: 'js/[name].js',
}

if (isProd) {
  plugins.push(
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /index.css$/g,
      cssProcessor: require("cssnano"),
      cssProcessorOptions: {
        discardComments: { removeAll: true },
        autoprefixer: {
          browsers: ["last 2 versions", "Safari > 8"],
          add: true,
        },
      },
      canPrint: true,
    }),
    new webpack.ContextReplacementPlugin(
      /moment[\/\\]locale$/,
      /(fr\.js|nl-be|nl\.js|en-gb|de\.js)/
    ),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new FileManagerPlugin({
      onEnd: {
        copy: [
          { source: "dist/css/index.css", destination: "dist/css/index.scss" },
          { source: "public/fonts", destination: "dist/fonts" },
        ],
      },
    })
  );

  entries.index = libraryBaseStyles
    .concat(libraryAllStyles)
    .concat(['./library/index.js'])

  // https://webpack.js.org/guides/author-libraries/
  output.library = 'nmbs-redesign-website'
  output.libraryTarget = 'umd'

  externals = [
    'autosize',
    // 'babel-polyfill',
    'gsap',
    'hammerjs',
    'imagesloaded',
    'inputmask',
    'masonry-layout',
    'moment',
    'packery',
    'picturefill',
    'pikaday',
    'prismjs',
    'promise-polyfill',
    'scrollmonitor',
    'whatwg-fetch',
    'wicg-inert',
  ]
} else {
  rules.push({
    test: /\.svg$/,
    include: path.join(__dirname, './library/basics/Icons'),
    loaders: [
      'svg-sprite-loader?' +
        JSON.stringify({
          name: 'icon-[name]',
          prefixize: true,
        }),
      'svgo-loader?' +
        JSON.stringify({
          plugins: [
            {removeTitle: true},
            {convertPathData: false},
            {removeUselessStrokeAndFill: true},
          ],
        }),
    ],
  })

  plugins.push(new webpack.LoaderOptionsPlugin({options: {}}))

  entries.library = libraryBaseStyles
    .concat(libraryAllStyles)
    .concat(['./library/index.js'])
  entries.docs = glob.sync('./docs/**/styles.scss').concat(['./docs/index.js'])
}

rules.push(
  {
    test: /\.js$/,
    // Default
    // exclude: [path.resolve(__dirname, 'node_modules')],
    // Specific
    include: [
      path.resolve(__dirname, 'library'),
      path.resolve(__dirname, 'docs'),
      path.resolve(__dirname, 'node_modules/dom7'),
      path.resolve(__dirname, 'node_modules/ssr-window'),
      path.resolve(__dirname, 'node_modules/swiper'),
    ],
    loader: 'babel-loader',
    query: {
      plugins: pluginsBabel,
      presets: [
        [
          'env',
          {
            targets: {
              browsers: ['last 2 versions', 'Safari > 8'],
            },
            debug: true,
            useBuiltIns: true,
          },
        ],
        'latest',
        'stage-2',
      ],
    },
  },

  // Loaders for other file types can go here
  {
    test: /\.scss$/,
    loader: ExtractTextPlugin.extract({
      fallback: 'style-loader',
      use: [
        {loader: 'css-loader', options: {url: false}},
        {loader: 'sass-loader'},
      ],
    }),
  }
)

console.log('\nWebpack ' + process.env.NODE_ENV + '\n (isProd: ' + isProd + ')')
module.exports = {
  entry: entries,
  output: output,
  externals: externals,
  module: {
    rules: rules,
  },

  plugins: plugins,

  devtool: isProd ? "source-map" : "inline-source-map",

  devServer: {
    contentBase: path.join(__dirname, "public/"),
    compress: true,
    overlay: true,
    inline: false,
    port: 3000,
  },
};

我的 Package.json

  "name": "es6-library",
  "version": "6.0.15",
  "description": "Pattern Library",
  "main": "dist/js/index.js",
  "module": "library/index.js",
  "scripts": {
    "docs": "gulp watch:docs",
    "nj": "gulp nunjucks",
    "dev": "cross-env NODE_ENV=local webpack serve",
    "build": "cross-env NODE_ENV=local ./node_modules/.bin/webpack && npm run versions",
    "build-prod": "cross-env NODE_ENV=production ./node_modules/.bin/webpack && npm run versions",
    "dist": "cross-env NODE_ENV=production ./node_modules/.bin/webpack && npm run versions",
    "versions": "node -p \"process.env.npm_package_version\" > ./public/version-npm.txt && node -p \"require('moment')().format('MMM/DD/YYYY HH:mm')\" > ./public/version.txt",
    "optimizesvg": "find ./library/basics/Icons -name '*.svg' -exec ./node_modules/.bin/svgo {} \\;",
    "build-push-staging": "npm run build && git add . && git commit -m \"build `date +\"%d/%m/%Y\"`\" && git push",
    "build-push-test": "npm run build && git add . && git commit -m \"require('moment')().format('MMM/DD/YYYY')\" && git push origin origin/test",
    "build-for-release": "npm run build-prod && npm run dist && git add . && git commit -m \"compile dist \"require('moment')().format('MMM/DD/YYYY')\"",
    "build-for-Deploy": "npm run build && git add . && git commit -m \"build \"require('moment')().format('MMM/DD/YYYY')\"",
    "build-push-production": "npm run build-for-Deploy && git push",
    "dist-push-production": "npm run build-for-release && git push && npm publish"
  },
  "author": "Amit",
  "license": "ISC",
  "dependencies": {
    "autosize": "^4.0.2",
    "babel-polyfill": "^6.26.0",
    "fuse.js": "^6.4.6",
    "gsap": "^3.6.1",
    "hammerjs": "^2.0.8",
    "imagesloaded": "^4.1.4",
    "inputmask": "4.0.9",
    "masonry-layout": "^4.2.2",
    "moment": "^2.26.0",
    "node-sass": "^5.0.0",
    "packery": "^2.1.2",
    "picturefill": "^3.0",
    "prismjs": "^1.15.0",
    "promise-polyfill": "^8.0",
    "scrollmonitor": "^1.2",
    "swiper": "^4.4.1",
    "whatwg-fetch": "^2.0.4",
    "wicg-inert": "^2.0"
  },
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-core": "^6.26.3",
    "babel-eslint": "^6.0.4",
    "babel-loader": "^7.1.5",
    "babel-plugin-lodash": "^3.3.4",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.8.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-latest": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "babel-register": "^6.26.0",
    "cross-env": "^7.0.3",
    "css-loader": "^5.2.4",
    "cssnano": "^5.0.2",
    "eslint": "^4.19.1",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.11",
    "filemanager-webpack-plugin": "^4.0.0",
    "glob": "^7.1.3",
    "gulp": "^3.9.1",
    "gulp-nunjucks-render": "git+https://github.com/carlosl/gulp-nunjucks-render.git",
    "gulp-plumber": "^1.2.0",
    "optimize-css-assets-webpack-plugin": "^3.2.0",
    "sass-loader": "6.0.7",
    "style-loader": "^0.21.0",
    "svg-sprite-loader": "0.3.1",
    "svgo": "^1.1.1",
    "svgo-loader": "^2.2.0",
    "webpack": "^5.36.2",
    "webpack-cli": "^4.6.0",
    "webpack-dev-server": "^3.11.2"
  }
}

这是我尝试启动服务器时遇到的错误(npm run dev

Webpack local (isProd: false) [webpack-cli] 无效的配置对象。Webpack 已使用与 API 模式不匹配的配置对象进行初始化。

  • configuration.module.rules[2] 应该是以下之一: ["..." | 对象{编译器?,依赖?,descriptionData?,强制?,排除?,生成器?,包括?,发行者?,发行者层?,层?,加载器?,mimetype?,oneOf?,选项?,解析器?,realResource?,解析?,资源?,resourceFragment?,resourceQuery?,规则?,sideEffects?,测试?,类型?,使用?}, ...] -> 一条规则。细节:
    • configuration.module.rules[2].loader 应该是一个非空字符串。-> 加载器请求。
4

0 回答 0