如何在 Next.js 中使用 webpack 5 配置?

Pet*_*r W 7 webpack next.js

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

我的环境:

  • 纱线@1.22.5
  • 节点@12.13.0

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

根据我所阅读的内容,我需要向package.json添加一个 resolutions 属性,如下所示:

"dependencies": {
    "next": "10.0.6",
    "react": "17.0.1",
    "react-dom": "17.0.1"
},
"resolutions": {
  "webpack": "5.21.2"
}
Run Code Online (Sandbox Code Playgroud)

然后在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;
  },
};
Run Code Online (Sandbox Code Playgroud)

当我yarn dev收到以下错误时:

- configuration[0] has an unknown property 'experiments'.
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*ila 20

从 Next.js v11 Webpack 5 开始,现在是所有 Next.js 应用程序的默认设置

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

对于 Next.js 的先前版本,您需要在 中为它设置一个标志next.config.js

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

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

module.exports = {
  // Note: no `future` key here
  webpack5: false,
}
Run Code Online (Sandbox Code Playgroud)

  • @juliomalves 是的,你快了 12 秒!不知道为什么选择我的答案:) (2认同)

jul*_*ves 17

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

您仍然可以通过将 设置webpack5falsein来使用 webpack 4 next.config.js

module.exports = {
    webpack5: false
}
Run Code Online (Sandbox Code Playgroud)

在 Next.js 11 之前,有一个future标志可以在next.config.js.

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


小智 5

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

next.config.js

添加下面的代码片段future flag

  future: {
    webpack5: true,
  }
Run Code Online (Sandbox Code Playgroud)

我的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,
  },
};
Run Code Online (Sandbox Code Playgroud)

特征

官方文档中提到的 webpack 5 的特性