/
base.ts
263 lines (248 loc) · 8.76 KB
/
base.ts
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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import fs from 'fs-extra';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import path from 'path';
import {Configuration} from 'webpack';
import {Props} from '@docusaurus/types';
import {
getCustomizableJSLoader,
getStyleLoaders,
getFileLoaderUtils,
getCustomBabelConfigFilePath,
getMinimizer,
} from './utils';
import {STATIC_DIR_NAME} from '../constants';
import {loadPluginsThemeAliases} from '../server/themes';
import {md5Hash} from '@docusaurus/utils';
const CSS_REGEX = /\.css$/;
const CSS_MODULE_REGEX = /\.module\.css$/;
export const clientDir = path.join(__dirname, '..', 'client');
const LibrariesToTranspile = [
'copy-text-to-clipboard', // contains optional catch binding, incompatible with recent versions of Edge
];
const LibrariesToTranspileRegex = new RegExp(
LibrariesToTranspile.map((libName) => `(node_modules/${libName})`).join('|'),
);
export function excludeJS(modulePath: string): boolean {
// always transpile client dir
if (modulePath.startsWith(clientDir)) {
return false;
}
// Don't transpile node_modules except any docusaurus npm package
return (
/node_modules/.test(modulePath) &&
!/(docusaurus)((?!node_modules).)*\.jsx?$/.test(modulePath) &&
!LibrariesToTranspileRegex.test(modulePath)
);
}
export function getDocusaurusAliases(): Record<string, string> {
const dirPath = path.resolve(__dirname, '../client/exports');
const extensions = ['.js', '.ts', '.tsx'];
const aliases: Record<string, string> = {};
fs.readdirSync(dirPath)
.filter((fileName) => extensions.includes(path.extname(fileName)))
.forEach((fileName) => {
const fileNameWithoutExtension = path.basename(
fileName,
path.extname(fileName),
);
const aliasName = `@docusaurus/${fileNameWithoutExtension}`;
aliases[aliasName] = path.resolve(dirPath, fileName);
});
return aliases;
}
export function createBaseConfig(
props: Props,
isServer: boolean,
minify: boolean = true,
): Configuration {
const {
outDir,
siteDir,
siteConfig,
siteConfigPath,
baseUrl,
generatedFilesDir,
routesPaths,
siteMetadata,
plugins,
} = props;
const totalPages = routesPaths.length;
const isProd = process.env.NODE_ENV === 'production';
const minimizeEnabled = minify && isProd && !isServer;
const useSimpleCssMinifier = process.env.USE_SIMPLE_CSS_MINIFIER === 'true';
const fileLoaderUtils = getFileLoaderUtils();
const name = isServer ? 'server' : 'client';
const mode = isProd ? 'production' : 'development';
const themeAliases = loadPluginsThemeAliases({siteDir, plugins});
return {
mode,
name,
cache: {
type: 'filesystem',
// Can we share the same cache across locales?
// Exploring that question at https://github.com/webpack/webpack/issues/13034
// name: `${name}-${mode}`,
name: `${name}-${mode}-${props.i18n.currentLocale}`,
// When version string changes, cache is evicted
version: [
siteMetadata.docusaurusVersion,
// Webpack does not evict the cache correctly on alias/swizzle change, so we force eviction.
// See https://github.com/webpack/webpack/issues/13627
md5Hash(JSON.stringify(themeAliases)),
].join('-'),
// When one of those modules/dependencies change (including transitive deps), cache is invalidated
buildDependencies: {
config: [
__filename,
path.join(__dirname, isServer ? 'server.js' : 'client.js'),
// Docusaurus config changes can affect MDX/JSX compilation, so we'd rather evict the cache.
// See https://github.com/questdb/questdb.io/issues/493
siteConfigPath,
],
},
},
output: {
pathinfo: false,
path: outDir,
filename: isProd ? 'assets/js/[name].[contenthash:8].js' : '[name].js',
chunkFilename: isProd
? 'assets/js/[name].[contenthash:8].js'
: '[name].js',
publicPath: baseUrl,
},
// Don't throw warning when asset created is over 250kb
performance: {
hints: false,
},
devtool: isProd ? undefined : 'eval-cheap-module-source-map',
resolve: {
unsafeCache: false, // not enabled, does not seem to improve perf much
extensions: ['.wasm', '.mjs', '.js', '.jsx', '.ts', '.tsx', '.json'],
symlinks: true, // see https://github.com/facebook/docusaurus/issues/3272
roots: [
// Allow resolution of url("/fonts/xyz.ttf") by webpack
// See https://webpack.js.org/configuration/resolve/#resolveroots
// See https://github.com/webpack-contrib/css-loader/issues/1256
path.join(siteDir, STATIC_DIR_NAME),
siteDir,
process.cwd(),
],
alias: {
'@site': siteDir,
'@generated': generatedFilesDir,
// Note: a @docusaurus alias would also catch @docusaurus/theme-common,
// so we use fine-grained aliases instead
// '@docusaurus': path.resolve(__dirname, '../client/exports'),
...getDocusaurusAliases(),
...themeAliases,
},
// This allows you to set a fallback for where Webpack should look for modules.
// We want `@docusaurus/core` own dependencies/`node_modules` to "win" if there is conflict
// Example: if there is core-js@3 in user's own node_modules, but core depends on
// core-js@2, we should use core-js@2.
modules: [
path.resolve(__dirname, '..', '..', 'node_modules'),
'node_modules',
path.resolve(fs.realpathSync(process.cwd()), 'node_modules'),
],
},
resolveLoader: {
modules: ['node_modules', path.join(siteDir, 'node_modules')],
},
optimization: {
removeAvailableModules: false,
// Only minimize client bundle in production because server bundle is only used for static site generation
minimize: minimizeEnabled,
minimizer: minimizeEnabled
? getMinimizer(useSimpleCssMinifier)
: undefined,
splitChunks: isServer
? false
: {
// Since the chunk name includes all origin chunk names it's recommended for production builds with long term caching to NOT include [name] in the filenames
name: false,
cacheGroups: {
// disable the built-in cacheGroups
default: false,
common: {
name: 'common',
minChunks: totalPages > 2 ? totalPages * 0.5 : 2,
priority: 40,
},
// Only create one CSS file to avoid
// problems with code-split CSS loading in different orders
// causing inconsistent/non-deterministic styling
// See https://github.com/facebook/docusaurus/issues/2006
styles: {
name: 'styles',
type: 'css/mini-extract',
chunks: `all`,
enforce: true,
priority: 50,
},
},
},
},
module: {
rules: [
fileLoaderUtils.rules.images(),
fileLoaderUtils.rules.fonts(),
fileLoaderUtils.rules.media(),
fileLoaderUtils.rules.svg(),
fileLoaderUtils.rules.otherAssets(),
{
test: /\.(j|t)sx?$/,
exclude: excludeJS,
use: [
getCustomizableJSLoader(siteConfig.webpack?.jsLoader)({
isServer,
babelOptions: getCustomBabelConfigFilePath(siteDir),
}),
],
},
{
test: CSS_REGEX,
exclude: CSS_MODULE_REGEX,
use: getStyleLoaders(isServer, {
importLoaders: 1,
sourceMap: !isProd,
}),
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: CSS_MODULE_REGEX,
use: getStyleLoaders(isServer, {
modules: {
localIdentName: isProd
? `[local]_[contenthash:base64:4]`
: `[local]_[path][name]`,
exportOnlyLocals: isServer,
},
importLoaders: 1,
sourceMap: !isProd,
}),
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: isProd
? 'assets/css/[name].[contenthash:8].css'
: '[name].css',
chunkFilename: isProd
? 'assets/css/[name].[contenthash:8].css'
: '[name].css',
// remove css order warnings if css imports are not sorted alphabetically
// see https://github.com/webpack-contrib/mini-css-extract-plugin/pull/422 for more reasoning
ignoreOrder: true,
}),
],
};
}