-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwithNext.js
67 lines (55 loc) · 2.58 KB
/
withNext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const RefreshWebpackPlugin = require("./RefreshWebpackPlugin");
module.exports = function withNext(nextConfig = {}) {
return Object.assign({}, nextConfig, {
webpack: (config, options) => {
const originalEntry = config.entry;
if (options.dev) {
config.entry = async () => {
const entries = await originalEntry();
if (entries["main.js"] && !entries["main.js"].includes(require.resolve("@my-react/react-refresh-tools/runtime"))) {
entries["main.js"].unshift(require.resolve("@my-react/react-refresh-tools/runtime"));
}
return entries;
};
config.plugins.push(new RefreshWebpackPlugin());
}
const { isServer, defaultLoaders } = options;
// Disable package exports field resolution in webpack. It can lead
// to dual package hazards where packages are imported twice: One
// commonjs version and one ESM version. This breaks hooks which have
// to rely on a singleton by design (nothing we can do about that).
// See #25 and https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_dual_package_hazard
// for more information.
const webpackVersion = options.webpack.version;
if (isServer && +webpackVersion.split(".")[0] >= 5) {
config.resolve.exportsFields = [];
}
if (!defaultLoaders) {
throw new Error("This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade");
}
// Move Preact into the framework chunk instead of duplicating in routes:
const splitChunks = config.optimization && config.optimization.splitChunks;
if (splitChunks && splitChunks.cacheGroups) {
const cacheGroups = splitChunks.cacheGroups;
const test = /[\\/]node_modules[\\/](@my-react|@my-react\/react-dom)[\\/]/;
if (cacheGroups.framework) {
cacheGroups["@my-react"] = Object.assign({}, cacheGroups.framework, {
test,
});
// if you want to merge the 2 small commons+framework chunks:
// cacheGroups.commons.name = 'framework';
}
}
if (typeof nextConfig.webpack === "function") {
config = nextConfig.webpack(config, options);
}
// Install webpack aliases:
const aliases = config.resolve.alias || (config.resolve.alias = {});
aliases["react"] = "@my-react/react";
aliases["react-dom$"] = "@my-react/react-dom";
aliases["react-dom/server$"] = "@my-react/react-dom/server";
aliases["react-dom/client$"] = "@my-react/react-dom/client";
return config;
},
});
};