UNPKG

2.62 kBJavaScriptView Raw
1const path = require('path');
2
3/**
4 * Stolen from https://stackoverflow.com/questions/10776600/testing-for-equality-of-regular-expressions
5 */
6function regexEqual (x, y) {
7 return (x instanceof RegExp) && (y instanceof RegExp) &&
8 (x.source === y.source) && (x.global === y.global) &&
9 (x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);
10}
11
12/**
13 * Actual Next.js plugin
14 */
15module.exports = (nextConfig = {}) => {
16 const { transpileModules = [] } = nextConfig;
17 const includes = transpileModules.map(module => (new RegExp(`${module}(?!.*node_modules)`)));
18 const excludes = [new RegExp(`node_modules(?!/(${transpileModules.join('|')})(?!.*node_modules))`)];
19
20 return Object.assign({}, nextConfig, {
21 webpack (config, options) {
22 // Safecheck for Next < 5.0
23 if (!options.defaultLoaders) {
24 throw new Error(
25 'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade'
26 );
27 }
28
29 // Avoid Webpack to resolve transpiled modules path to their real path
30 config.resolve.symlinks = false;
31
32 config.externals = config.externals.map(external => {
33 if (typeof external !== 'function') return external;
34 return (ctx, req, cb) => {
35 return includes.find(include =>
36 req.startsWith('.')
37 ? include.test(path.resolve(ctx, req))
38 : include.test(req)
39 )
40 ? cb()
41 : external(ctx, req, cb);
42 };
43 });
44
45 // Add a rule to include and parse all modules
46 config.module.rules.push({
47 test: /\.+(js|jsx|ts|tsx)$/,
48 loader: options.defaultLoaders.babel,
49 include: includes
50 });
51
52 if (typeof nextConfig.webpack === 'function') {
53 return nextConfig.webpack(config, options);
54 }
55
56 return config;
57 },
58
59 // webpackDevMiddleware needs to be told to watch the changes in the
60 // transpiled modules directories
61 webpackDevMiddleware (config) {
62 // Replace /node_modules/ by the new exclude RegExp (including the modules
63 // that are going to be transpiled)
64 // https://github.com/zeit/next.js/blob/815f2e91386a0cd046c63cbec06e4666cff85971/packages/next/server/hot-reloader.js#L335
65 const ignored = config.watchOptions.ignored.filter(
66 regexp => !regexEqual(regexp, /[\\/]node_modules[\\/]/)
67 ).concat(excludes);
68
69 config.watchOptions.ignored = ignored;
70
71 if (typeof nextConfig.webpackDevMiddleware === 'function') {
72 return nextConfig.webpackDevMiddleware(config);
73 }
74
75 return config;
76 }
77 });
78};