【问题标题】:How to use webpack 5 configs in Next.js?如何在 Next.js 中使用 webpack 5 配置?
【发布时间】:2021-05-13 09:15:38
【问题描述】:

我正在尝试将 experiments 添加到 webpack 配置中,但无法确定我做错了什么。

我的环境:

  • yarn@1.22.5
  • node@12.13.0

我用npx create-next-app blog创建了一个全新的下一个应用程序

基于 I have read 我需要向 package.json 添加一个 resolutions 属性,如下所示:

"dependencies": {
    "next": "10.0.6",
    "react": "17.0.1",
    "react-dom": "17.0.1"
},
"resolutions": {
  "webpack": "5.21.2"
}

然后在 next.config.js 我有以下内容:

const webpack = require("webpack");
console.log(webpack.version); // 5.21.2
module.exports = {
  webpack: function (config, options) {
    console.log(options.webpack.version); // 4.44.1
    config.experiments = {};
    return config;
  },
};

当我yarn dev 时出现以下错误:

- configuration[0] has an unknown property 'experiments'.

如果您注意到所需的模块 webpack 版本是 5.21.2,但在配置设置中使用的版本是 4.44.1

【问题讨论】:

  • 下一个版本是什么?
  • @felixmosh 10.0.6

标签: javascript webpack next.js


【解决方案1】:

从 Next.js v11 Webpack 5 is now the default 开始,适用于所有 Next.js 应用程序:

Webpack 5 现在是所有 Next.js 应用程序的默认设置。如果您没有自定义 webpack 配置,您的应用程序已经在使用 webpack 5。如果您有自定义 webpack 配置,您可以参考Next.js webpack 5 documentation 获取升级指南。

对于 Next.js 的早期版本,您需要在 next.config.js 中为其设置一个标志:

module.exports = {
  future: {
    webpack5: true,
  },
  webpack: function (config, options) {
    config.experiments = {};
    return config;
  },
};

通过添加webpack5: false 标志,您仍然可以在升级到最新版本的 Next.js 时使用 webpack 4

module.exports = {
  // Note: no `future` key here
  webpack5: false,
}

【讨论】:

  • 我确实领先你几秒钟,但还是有人赞成!
  • @juliomalves 或 Danila 该未来财产的文档在哪里?
  • @juliomalves 是的,你快了 12 秒!不知道为什么我的答案被选中:)
【解决方案2】:

由于现在默认使用 Next.js 11 webpack 5,无需额外配置。

您仍然可以通过在next.config.js 中将webpack5 设置为false 来使用webpack 4。

module.exports = {
    webpack5: false
}

在 Next.js 11 之前,有一个 future 标志可以在 next.config.js 中为 Webpack 5 启用。

module.exports = {
    future: {
        webpack5: true
    },
    webpack: function (config, options) {
        console.log(options.webpack.version); // 5.18.0
        config.experiments = {};
        return config;
    }
};

【讨论】:

  • 谢谢你的回答,我也给你一个+1回答
  • Next.js 现在记录了这一点:Webpack 5 Adoption
【解决方案3】:

官方文档:https://nextjs.org/docs/messages/webpack5

转到next.config.js

添加下面的 sn-p 和 future flag

  future: {
    webpack5: true,
  }

我的next.config.js

const path = require("path");

module.exports = {
  trailingSlash: true,
  webpackDevMiddleware: (config) => {
    config.watchOptions = {
      poll: 1000,
      aggregateTimeout: 300,
    };

    return config;
  },
  sassOptions: {
    includePaths: [path.join(__dirname, "styles")],
  },
  future: {
    webpack5: true,
  },
};

特点

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 2021-09-28
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多