forked from wellcometrust/next-plugin-transpile-modules
-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathnext-transpile-modules.js
285 lines (248 loc) · 10.8 KB
/
next-transpile-modules.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* disclaimer:
*
* THIS PLUGIN IS A BIG HACK.
*
* Don't even try to reason about the quality of the following lines of code.
*
* ---
*
* We intentionally do not use experimental.transpilePackages (yet) as its API
* may change and we want to avoid breaking changes while the Next.js figures
* this all out.
*/
const path = require('path');
const process = require('process');
const enhancedResolve = require('enhanced-resolve');
// Use me when needed
// const util = require('util');
// const inspect = (object) => {
// console.log(util.inspect(object, { showHidden: false, depth: null }));
// };
const CWD = process.cwd();
/**
* Check if two regexes are equal
* Stolen from https://stackoverflow.com/questions/10776600/testing-for-equality-of-regular-expressions
*
* @param {RegExp} x
* @param {RegExp} y
* @returns {boolean}
*/
const regexEqual = (x, y) => {
return (
x instanceof RegExp &&
y instanceof RegExp &&
x.source === y.source &&
x.global === y.global &&
x.ignoreCase === y.ignoreCase &&
x.multiline === y.multiline
);
};
/**
* Logger for the debug mode
* @param {boolean} enable enable the logger or not
* @returns {(message: string, force: boolean) => void}
*/
const createLogger = (enable) => {
return (message, force) => {
if (enable || force) console.info(`next-transpile-modules - ${message}`);
};
};
/**
* Matcher function for webpack to decide which modules to transpile
* TODO: could be simplified
*
* @param {string[]} modulesToTranspile
* @param {function} logger
* @returns {(path: string) => boolean}
*/
const createWebpackMatcher = (modulesToTranspile, logger = createLogger(false)) => {
// create an array of tuples with each passed in module to transpile and its node_modules depth
// example: ['/full/path/to/node_modules/button/node_modules/icon', 2]
const modulePathsWithDepth = modulesToTranspile.map((modulePath) => [
modulePath,
(modulePath.match(/node_modules/g) || []).length,
]);
return (filePath) => {
const nodeModulesDepth = (filePath.match(/node_modules/g) || []).length;
return modulePathsWithDepth.some(([modulePath, moduleDepth]) => {
// Ensure we aren't implicitly transpiling nested dependencies by comparing depths of modules to be transpiled and the module being checked
const transpiled = filePath.startsWith(modulePath) && nodeModulesDepth === moduleDepth;
if (transpiled) logger(`transpiled: ${filePath}`);
return transpiled;
});
};
};
/**
* Transpile modules with Next.js Babel configuration
* @param {string[]} modules
* @param {{resolveSymlinks?: boolean, debug?: boolean, __unstable_matcher?: (path: string) => boolean}} options
*/
const withTmInitializer = (modules = [], options = {}) => {
/**
* @template T
* @param { T } nextConfig
* @returns { T | undefined }
*/
const withTM = (nextConfig = {}) => {
if (modules.length === 0) return nextConfig;
const resolveSymlinks = 'resolveSymlinks' in options ? options.resolveSymlinks : true;
const debug = options.debug || false;
const logger = createLogger(debug);
/**
* Our own Node.js resolver that can ignore symlinks resolution and can support
* PnP
*/
const resolve = enhancedResolve.create.sync({
symlinks: resolveSymlinks,
extensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.css', '.scss', '.sass'],
mainFields: ['main', 'module', 'source'],
// Is it right? https://github.com/webpack/enhanced-resolve/issues/283#issuecomment-775162497
conditionNames: ['require'],
exportsFields: [], // we do that because 'package.json' is usually not present in exports
});
/**
* Return the root path (package.json directory) of a given module
* @param {string} module
* @returns {string}
*/
const getPackageRootDirectory = (module) => {
try {
const packageLookupDirectory = resolve(CWD, path.join(module, 'package.json'));
return path.dirname(packageLookupDirectory);
} catch (err) {
throw new Error(
`next-transpile-modules - an unexpected error happened when trying to resolve "${module}". Are you sure the name of the module you are trying to transpile is correct, and it has a package.json with a "main" or an "exports" field?\n${err}`,
);
}
};
logger(`trying to resolve the following modules:\n${modules.map((mod) => ` - ${mod}`).join('\n')}`);
// Resolve modules to their real paths
const modulesPaths = modules.map(getPackageRootDirectory);
logger(`the following paths will get transpiled:\n${modulesPaths.map((mod) => ` - ${mod}`).join('\n')}`);
// Generate Webpack condition for the passed modules
// https://webpack.js.org/configuration/module/#ruleinclude
const matcher = options.__unstable_matcher || createWebpackMatcher(modulesPaths, logger);
return Object.assign({}, nextConfig, {
webpack(config, options) {
// Safecheck for Next < 5.0
if (!options.defaultLoaders) {
throw new Error(
'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade',
);
}
if (resolveSymlinks !== undefined) {
// Avoid Webpack to resolve transpiled modules path to their real path as
// we want to test modules from node_modules only. If it was enabled,
// modules in node_modules installed via symlink would then not be
// transpiled.
config.resolve.symlinks = resolveSymlinks;
}
// Since Next.js 8.1.0, config.externals is undefined
if (Array.isArray(config.externals)) {
config.externals = config.externals.map((external) => {
if (typeof external !== 'function') return external;
return async (options) => {
const externalResult = await external(options);
if (externalResult) {
try {
const resolve = options.getResolve();
const resolved = await resolve(options.context, options.request);
if (modulesPaths.some((mod) => resolved.startsWith(mod))) return;
} catch (e) {}
}
return externalResult;
};
});
}
// Add a rule to include and parse all modules (js & ts)
config.module.rules.push({
test: /\.+(js|jsx|mjs|ts|tsx)$/,
use: options.defaultLoaders.babel,
include: matcher,
type: 'javascript/auto',
});
if (resolveSymlinks === false) {
// IMPROVE ME: we are losing all the cache on node_modules, which is terrible
// The problem is managedPaths does not allow to isolate specific specific folders
config.snapshot = Object.assign(config.snapshot || {}, {
managedPaths: [],
});
}
// Support CSS modules + global in node_modules
// TODO ask Next.js maintainer to expose the css-loader via defaultLoaders
const nextCssLoaders = config.module.rules.find((rule) => typeof rule.oneOf === 'object');
// .module.css
if (nextCssLoaders) {
const nextCssLoader = nextCssLoaders.oneOf.find(
(rule) => rule.sideEffects === false && regexEqual(rule.test, /\.module\.css$/),
);
const nextSassLoader = nextCssLoaders.oneOf.find(
(rule) => rule.sideEffects === false && regexEqual(rule.test, /\.module\.(scss|sass)$/),
);
// backwards compatibility with Next.js 13.0 (broke in 13.0.1)
// https://github.com/vercel/next.js/pull/42106/files
if (nextCssLoader && nextCssLoader.issuer != null) {
nextCssLoader.issuer.or = nextCssLoader.issuer.and ? nextCssLoader.issuer.and.concat(matcher) : matcher;
delete nextCssLoader.issuer.not;
delete nextCssLoader.issuer.and;
}
// backwards compatibility with Next.js 13.0 (broke in 13.0.1)
// https://github.com/vercel/next.js/pull/42106/files
if (nextSassLoader && nextSassLoader.issuer != null) {
nextSassLoader.issuer.or = nextSassLoader.issuer.and ? nextSassLoader.issuer.and.concat(matcher) : matcher;
delete nextSassLoader.issuer.not;
delete nextSassLoader.issuer.and;
}
}
// Add support for Global CSS imports in transpiled modules
if (nextCssLoaders) {
const nextGlobalCssLoader = nextCssLoaders.oneOf.find(
(rule) => rule.sideEffects === true && regexEqual(rule.test, /(?<!\.module)\.css$/),
);
if (nextGlobalCssLoader) {
nextGlobalCssLoader.issuer = {
or: nextGlobalCssLoader.issuer ? [matcher, nextGlobalCssLoader.issuer] : [matcher],
};
nextGlobalCssLoader.include = {
or: nextGlobalCssLoader.include ? [...modulesPaths, nextGlobalCssLoader.include] : modulesPaths,
};
} else if (!options.isServer) {
// Note that Next.js ignores global CSS imports on the server
console.warn('next-transpile-modules - could not find default CSS rule, global CSS imports may not work');
}
const nextGlobalSassLoader = nextCssLoaders.oneOf.find(
(rule) => rule.sideEffects === true && regexEqual(rule.test, /(?<!\.module)\.(scss|sass)$/),
);
// FIXME: SASS works only when using a custom _app.js file.
// See https://github.com/vercel/next.js/blob/24c3929ec46edfef8fb7462a17edc767a90b5d2b/packages/next/build/webpack/config/blocks/css/index.ts#L211
if (nextGlobalSassLoader) {
nextGlobalSassLoader.issuer = {
or: nextGlobalSassLoader.issuer ? [matcher, nextGlobalSassLoader.issuer] : [matcher],
};
} else if (!options.isServer) {
// Note that Next.js ignores global SASS imports on the server
console.info('next-transpile-modules - global SASS imports only work with a custom _app.js file');
}
}
// Make hot reloading work!
// FIXME: not working on Wepback 5
// https://github.com/vercel/next.js/issues/13039
const watchOptionsIgnored = Array.isArray(config.watchOptions.ignored)
? config.watchOptions.ignored
: [config.watchOptions.ignored];
config.watchOptions.ignored = [
...watchOptionsIgnored.filter((pattern) => pattern !== '**/node_modules/**'),
`**node_modules/{${modules.map((mod) => `!(${mod})`).join(',')}}/**/*`,
];
// Overload the Webpack config if it was already overloaded
if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options);
}
return config;
},
});
};
return withTM;
};
module.exports = withTmInitializer;