Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

javascript - How to use webpack 5 configs in Next.js?

I am trying to add experiments to the webpack config but am unable to determine what I am doing wrong.

my environment:

I created a brand new next app with npx create-next-app blog

Based on what I have read I need to add a resolutions property to the package.json like so:

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

And then in next.config.js I have the following:

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;
  },
};

and when I yarn dev I get the following error:

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

If you notice the required module webpack version is 5.21.2 but the version being used inside the config settings is 4.44.1.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Starting from Next.js v11 Webpack 5 is now the default for all Next.js applications:

Webpack 5 is now the default for all Next.js applications. If you did not have custom webpack configuration your application is already using webpack 5. If you do have custom webpack configuration you can refer to the Next.js webpack 5 documentation for upgrading guidance.

For prior versions of Next.js you need to set a flag for it in next.config.js:

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

And you can still use webpack 4 while upgrading to the latest version of Next.js by adding the webpack5: false flag

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...