@docusaurus/core 3.1.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/bin/docusaurus.mjs +10 -5
  2. package/lib/client/{serverRenderer.d.ts → renderToHtml.d.ts} +1 -1
  3. package/lib/client/{serverRenderer.js → renderToHtml.js} +1 -1
  4. package/lib/client/serverEntry.d.ts +3 -4
  5. package/lib/client/serverEntry.js +12 -113
  6. package/lib/client/theme-fallback/Error/index.js +22 -8
  7. package/lib/commands/build.d.ts +3 -3
  8. package/lib/commands/build.js +133 -112
  9. package/lib/commands/deploy.d.ts +2 -2
  10. package/lib/commands/deploy.js +3 -3
  11. package/lib/commands/external.js +2 -2
  12. package/lib/commands/serve.d.ts +2 -2
  13. package/lib/commands/serve.js +4 -4
  14. package/lib/commands/{start.d.ts → start/start.d.ts} +3 -3
  15. package/lib/commands/start/start.js +47 -0
  16. package/lib/commands/start/utils.d.ts +31 -0
  17. package/lib/commands/start/utils.js +87 -0
  18. package/lib/commands/start/watcher.d.ts +42 -0
  19. package/lib/commands/start/watcher.js +78 -0
  20. package/lib/commands/start/webpack.d.ts +15 -0
  21. package/lib/commands/start/webpack.js +133 -0
  22. package/lib/commands/swizzle/common.d.ts +1 -0
  23. package/lib/commands/swizzle/common.js +1 -0
  24. package/lib/commands/swizzle/context.js +2 -2
  25. package/lib/commands/swizzle/index.js +32 -3
  26. package/lib/commands/writeHeadingIds.js +2 -2
  27. package/lib/commands/writeTranslations.d.ts +2 -2
  28. package/lib/commands/writeTranslations.js +3 -3
  29. package/lib/index.d.ts +1 -1
  30. package/lib/index.js +1 -1
  31. package/lib/server/brokenLinks.js +4 -4
  32. package/lib/server/clientModules.d.ts +1 -1
  33. package/lib/server/clientModules.js +3 -3
  34. package/lib/server/codegen/codegen.d.ts +20 -0
  35. package/lib/server/codegen/codegen.js +65 -0
  36. package/lib/server/codegen/codegenRoutes.d.ts +49 -0
  37. package/lib/server/codegen/codegenRoutes.js +190 -0
  38. package/lib/server/configValidation.js +6 -4
  39. package/lib/server/i18n.d.ts +2 -2
  40. package/lib/server/i18n.js +20 -2
  41. package/lib/server/plugins/actions.d.ts +19 -0
  42. package/lib/server/plugins/actions.js +62 -0
  43. package/lib/server/plugins/init.js +3 -3
  44. package/lib/server/plugins/plugins.d.ts +21 -0
  45. package/lib/server/plugins/plugins.js +188 -0
  46. package/lib/server/plugins/pluginsUtils.d.ts +16 -0
  47. package/lib/server/plugins/pluginsUtils.js +75 -0
  48. package/lib/server/plugins/routeConfig.d.ts +1 -1
  49. package/lib/server/plugins/routeConfig.js +4 -4
  50. package/lib/server/plugins/synthetic.d.ts +3 -3
  51. package/lib/server/plugins/synthetic.js +0 -2
  52. package/lib/server/routes.d.ts +3 -45
  53. package/lib/server/routes.js +16 -168
  54. package/lib/server/{index.d.ts → site.d.ts} +12 -5
  55. package/lib/server/site.js +164 -0
  56. package/lib/server/siteMetadata.d.ts +5 -4
  57. package/lib/server/siteMetadata.js +14 -10
  58. package/lib/server/translations/translations.d.ts +9 -2
  59. package/lib/server/translations/translations.js +21 -4
  60. package/lib/server/utils.d.ts +0 -2
  61. package/lib/server/utils.js +1 -9
  62. package/lib/ssg.d.ts +31 -0
  63. package/lib/ssg.js +167 -0
  64. package/lib/templates/templates.d.ts +28 -0
  65. package/lib/templates/templates.js +63 -0
  66. package/lib/utils.d.ts +9 -0
  67. package/lib/utils.js +78 -0
  68. package/lib/webpack/base.d.ts +5 -1
  69. package/lib/webpack/base.js +4 -6
  70. package/lib/webpack/client.d.ts +15 -1
  71. package/lib/webpack/client.js +78 -23
  72. package/lib/webpack/minification.d.ts +8 -0
  73. package/lib/webpack/minification.js +97 -0
  74. package/lib/webpack/server.d.ts +5 -3
  75. package/lib/webpack/server.js +41 -50
  76. package/lib/webpack/utils.d.ts +13 -4
  77. package/lib/webpack/utils.js +27 -83
  78. package/package.json +13 -11
  79. package/lib/commands/start.js +0 -212
  80. package/lib/server/index.js +0 -154
  81. package/lib/server/plugins/index.d.ts +0 -18
  82. package/lib/server/plugins/index.js +0 -106
  83. /package/lib/{webpack/templates/index.html.template.ejs → templates/dev.html.template.ejs} +0 -0
  84. /package/lib/{webpack/templates → templates}/ssr.html.template.d.ts +0 -0
  85. /package/lib/{webpack/templates → templates}/ssr.html.template.js +0 -0
package/lib/utils.js ADDED
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PerfLogger = exports.PerfDebuggingEnabled = void 0;
4
+ const tslib_1 = require("tslib");
5
+ /**
6
+ * Copyright (c) Facebook, Inc. and its affiliates.
7
+ *
8
+ * This source code is licensed under the MIT license found in the
9
+ * LICENSE file in the root directory of this source tree.
10
+ */
11
+ const async_hooks_1 = require("async_hooks");
12
+ const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
13
+ // For now this is a private env variable we use internally
14
+ // But we'll want to expose this feature officially some day
15
+ exports.PerfDebuggingEnabled = !!process.env.DOCUSAURUS_PERF_LOGGER;
16
+ const Thresholds = {
17
+ min: 5,
18
+ yellow: 100,
19
+ red: 1000,
20
+ };
21
+ const PerfPrefix = logger_1.default.yellow(`[PERF] `);
22
+ // This is what enables to "see the parent stack" for each log
23
+ // Parent1 > Parent2 > Parent3 > child trace
24
+ const ParentPrefix = new async_hooks_1.AsyncLocalStorage();
25
+ function applyParentPrefix(label) {
26
+ const parentPrefix = ParentPrefix.getStore();
27
+ return parentPrefix ? `${parentPrefix} > ${label}` : label;
28
+ }
29
+ function createPerfLogger() {
30
+ if (!exports.PerfDebuggingEnabled) {
31
+ const noop = () => { };
32
+ return {
33
+ start: noop,
34
+ end: noop,
35
+ log: noop,
36
+ async: async (_label, asyncFn) => asyncFn(),
37
+ };
38
+ }
39
+ const formatDuration = (duration) => {
40
+ if (duration > Thresholds.red) {
41
+ return logger_1.default.red(`${(duration / 1000).toFixed(2)} seconds!`);
42
+ }
43
+ else if (duration > Thresholds.yellow) {
44
+ return logger_1.default.yellow(`${duration.toFixed(2)} ms`);
45
+ }
46
+ else {
47
+ return logger_1.default.green(`${duration.toFixed(2)} ms`);
48
+ }
49
+ };
50
+ const logDuration = (label, duration) => {
51
+ if (duration < Thresholds.min) {
52
+ return;
53
+ }
54
+ console.log(`${PerfPrefix + label} - ${formatDuration(duration)}`);
55
+ };
56
+ const start = (label) => performance.mark(label);
57
+ const end = (label) => {
58
+ const { duration } = performance.measure(label);
59
+ performance.clearMarks(label);
60
+ logDuration(applyParentPrefix(label), duration);
61
+ };
62
+ const log = (label) => console.log(PerfPrefix + applyParentPrefix(label));
63
+ const async = async (label, asyncFn) => {
64
+ const finalLabel = applyParentPrefix(label);
65
+ const before = performance.now();
66
+ const result = await ParentPrefix.run(finalLabel, () => asyncFn());
67
+ const duration = performance.now() - before;
68
+ logDuration(finalLabel, duration);
69
+ return result;
70
+ };
71
+ return {
72
+ start,
73
+ end,
74
+ log,
75
+ async,
76
+ };
77
+ }
78
+ exports.PerfLogger = createPerfLogger();
@@ -8,4 +8,8 @@ import type { Configuration } from 'webpack';
8
8
  import type { Props } from '@docusaurus/types';
9
9
  export declare const clientDir: string;
10
10
  export declare function excludeJS(modulePath: string): boolean;
11
- export declare function createBaseConfig(props: Props, isServer: boolean, minify?: boolean): Promise<Configuration>;
11
+ export declare function createBaseConfig({ props, isServer, minify, }: {
12
+ props: Props;
13
+ isServer: boolean;
14
+ minify: boolean;
15
+ }): Promise<Configuration>;
@@ -13,6 +13,7 @@ const path_1 = tslib_1.__importDefault(require("path"));
13
13
  const mini_css_extract_plugin_1 = tslib_1.__importDefault(require("mini-css-extract-plugin"));
14
14
  const utils_1 = require("@docusaurus/utils");
15
15
  const utils_2 = require("./utils");
16
+ const minification_1 = require("./minification");
16
17
  const aliases_1 = require("./aliases");
17
18
  const CSS_REGEX = /\.css$/i;
18
19
  const CSS_MODULE_REGEX = /\.module\.css$/i;
@@ -32,12 +33,11 @@ function excludeJS(modulePath) {
32
33
  !LibrariesToTranspileRegex.test(modulePath));
33
34
  }
34
35
  exports.excludeJS = excludeJS;
35
- async function createBaseConfig(props, isServer, minify = true) {
36
+ async function createBaseConfig({ props, isServer, minify, }) {
36
37
  const { outDir, siteDir, siteConfig, siteConfigPath, baseUrl, generatedFilesDir, routesPaths, siteMetadata, plugins, } = props;
37
38
  const totalPages = routesPaths.length;
38
39
  const isProd = process.env.NODE_ENV === 'production';
39
- const minimizeEnabled = minify && isProd && !isServer;
40
- const useSimpleCssMinifier = process.env.USE_SIMPLE_CSS_MINIFIER === 'true';
40
+ const minimizeEnabled = minify && isProd;
41
41
  const fileLoaderUtils = (0, utils_1.getFileLoaderUtils)();
42
42
  const name = isServer ? 'server' : 'client';
43
43
  const mode = isProd ? 'production' : 'development';
@@ -124,9 +124,7 @@ async function createBaseConfig(props, isServer, minify = true) {
124
124
  // Only minimize client bundle in production because server bundle is only
125
125
  // used for static site generation
126
126
  minimize: minimizeEnabled,
127
- minimizer: minimizeEnabled
128
- ? (0, utils_2.getMinimizer)(useSimpleCssMinifier)
129
- : undefined,
127
+ minimizer: minimizeEnabled ? (0, minification_1.getMinimizer)() : undefined,
130
128
  splitChunks: isServer
131
129
  ? false
132
130
  : {
@@ -6,4 +6,18 @@
6
6
  */
7
7
  import type { Props } from '@docusaurus/types';
8
8
  import type { Configuration } from 'webpack';
9
- export default function createClientConfig(props: Props, minify?: boolean, hydrate?: boolean): Promise<Configuration>;
9
+ export declare function createStartClientConfig({ props, minify, poll, }: {
10
+ props: Props;
11
+ minify: boolean;
12
+ poll: number | boolean | undefined;
13
+ }): Promise<{
14
+ clientConfig: Configuration;
15
+ }>;
16
+ export declare function createBuildClientConfig({ props, minify, bundleAnalyzer, }: {
17
+ props: Props;
18
+ minify: boolean;
19
+ bundleAnalyzer: boolean;
20
+ }): Promise<{
21
+ config: Configuration;
22
+ clientManifestPath: string;
23
+ }>;
@@ -6,19 +6,36 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.createBuildClientConfig = exports.createStartClientConfig = void 0;
9
10
  const tslib_1 = require("tslib");
10
11
  const path_1 = tslib_1.__importDefault(require("path"));
11
12
  const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
12
13
  const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
13
14
  const webpackbar_1 = tslib_1.__importDefault(require("webpackbar"));
14
- const webpack_1 = require("webpack");
15
+ const webpack_1 = tslib_1.__importDefault(require("webpack"));
16
+ const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
17
+ const react_loadable_ssr_addon_v5_slorber_1 = tslib_1.__importDefault(require("react-loadable-ssr-addon-v5-slorber"));
18
+ const html_webpack_plugin_1 = tslib_1.__importDefault(require("html-webpack-plugin"));
15
19
  const base_1 = require("./base");
16
20
  const ChunkAssetPlugin_1 = tslib_1.__importDefault(require("./plugins/ChunkAssetPlugin"));
17
21
  const utils_1 = require("./utils");
18
- async function createClientConfig(props, minify = true, hydrate = true) {
19
- const isBuilding = process.argv[2] === 'build';
20
- const config = await (0, base_1.createBaseConfig)(props, false, minify);
21
- const clientConfig = (0, webpack_merge_1.default)(config, {
22
+ const CleanWebpackPlugin_1 = tslib_1.__importDefault(require("./plugins/CleanWebpackPlugin"));
23
+ // When building, include the plugin to force terminate building if errors
24
+ // happened in the client bundle.
25
+ class ForceTerminatePlugin {
26
+ apply(compiler) {
27
+ compiler.hooks.done.tap('client:done', (stats) => {
28
+ if (stats.hasErrors()) {
29
+ const errorsWarnings = stats.toJson('errors-warnings');
30
+ logger_1.default.error(`Client bundle compiled with errors therefore further build is impossible.\n${(0, utils_1.formatStatsErrorMessage)(errorsWarnings)}`);
31
+ process.exit(1);
32
+ }
33
+ });
34
+ }
35
+ }
36
+ async function createBaseClientConfig({ props, hydrate, minify, }) {
37
+ const baseConfig = await (0, base_1.createBaseConfig)({ props, isServer: false, minify });
38
+ return (0, webpack_merge_1.default)(baseConfig, {
22
39
  // Useless, disabled on purpose (errors on existing sites with no
23
40
  // browserslist config)
24
41
  // target: 'browserslist',
@@ -29,7 +46,7 @@ async function createClientConfig(props, minify = true, hydrate = true) {
29
46
  runtimeChunk: true,
30
47
  },
31
48
  plugins: [
32
- new webpack_1.DefinePlugin({
49
+ new webpack_1.default.DefinePlugin({
33
50
  'process.env.HYDRATE_CLIENT_ENTRY': JSON.stringify(hydrate),
34
51
  }),
35
52
  new ChunkAssetPlugin_1.default(),
@@ -39,21 +56,59 @@ async function createClientConfig(props, minify = true, hydrate = true) {
39
56
  }),
40
57
  ],
41
58
  });
42
- // When building, include the plugin to force terminate building if errors
43
- // happened in the client bundle.
44
- if (isBuilding) {
45
- clientConfig.plugins?.push({
46
- apply: (compiler) => {
47
- compiler.hooks.done.tap('client:done', (stats) => {
48
- if (stats.hasErrors()) {
49
- const errorsWarnings = stats.toJson('errors-warnings');
50
- logger_1.default.error(`Client bundle compiled with errors therefore further build is impossible.\n${(0, utils_1.formatStatsErrorMessage)(errorsWarnings)}`);
51
- process.exit(1);
52
- }
53
- });
54
- },
55
- });
56
- }
57
- return clientConfig;
58
59
  }
59
- exports.default = createClientConfig;
60
+ // client config when running "docusaurus start"
61
+ async function createStartClientConfig({ props, minify, poll, }) {
62
+ const { siteConfig, headTags, preBodyTags, postBodyTags } = props;
63
+ const clientConfig = (0, webpack_merge_1.default)(await createBaseClientConfig({
64
+ props,
65
+ minify,
66
+ hydrate: false,
67
+ }), {
68
+ watchOptions: {
69
+ ignored: /node_modules\/(?!@docusaurus)/,
70
+ poll,
71
+ },
72
+ infrastructureLogging: {
73
+ // Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
74
+ level: 'warn',
75
+ },
76
+ plugins: [
77
+ // Generates an `index.html` file with the <script> injected.
78
+ new html_webpack_plugin_1.default({
79
+ template: path_1.default.join(__dirname, '../templates/dev.html.template.ejs'),
80
+ // So we can define the position where the scripts are injected.
81
+ inject: false,
82
+ filename: 'index.html',
83
+ title: siteConfig.title,
84
+ headTags,
85
+ preBodyTags,
86
+ postBodyTags,
87
+ }),
88
+ ],
89
+ });
90
+ return { clientConfig };
91
+ }
92
+ exports.createStartClientConfig = createStartClientConfig;
93
+ // client config when running "docusaurus build"
94
+ async function createBuildClientConfig({ props, minify, bundleAnalyzer, }) {
95
+ // Apply user webpack config.
96
+ const { generatedFilesDir } = props;
97
+ const clientManifestPath = path_1.default.join(generatedFilesDir, 'client-manifest.json');
98
+ const config = (0, webpack_merge_1.default)(await createBaseClientConfig({ props, minify, hydrate: true }), {
99
+ plugins: [
100
+ new ForceTerminatePlugin(),
101
+ // Remove/clean build folders before building bundles.
102
+ new CleanWebpackPlugin_1.default({ verbose: false }),
103
+ // Visualize size of webpack output files with an interactive zoomable
104
+ // tree map.
105
+ bundleAnalyzer && new webpack_bundle_analyzer_1.BundleAnalyzerPlugin(),
106
+ // Generate client manifests file that will be used for server bundle.
107
+ new react_loadable_ssr_addon_v5_slorber_1.default({
108
+ filename: clientManifestPath,
109
+ }),
110
+ ].filter((x) => Boolean(x)),
111
+ });
112
+ return { config, clientManifestPath };
113
+ }
114
+ exports.createBuildClientConfig = createBuildClientConfig;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { WebpackPluginInstance } from 'webpack';
8
+ export declare function getMinimizer(): WebpackPluginInstance[];
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.getMinimizer = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const terser_webpack_plugin_1 = tslib_1.__importDefault(require("terser-webpack-plugin"));
12
+ const css_minimizer_webpack_plugin_1 = tslib_1.__importDefault(require("css-minimizer-webpack-plugin"));
13
+ // See https://github.com/webpack-contrib/terser-webpack-plugin#parallel
14
+ function getTerserParallel() {
15
+ let terserParallel = true;
16
+ if (process.env.TERSER_PARALLEL === 'false') {
17
+ terserParallel = false;
18
+ }
19
+ else if (process.env.TERSER_PARALLEL &&
20
+ parseInt(process.env.TERSER_PARALLEL, 10) > 0) {
21
+ terserParallel = parseInt(process.env.TERSER_PARALLEL, 10);
22
+ }
23
+ return terserParallel;
24
+ }
25
+ function getJsMinifierPlugin() {
26
+ return new terser_webpack_plugin_1.default({
27
+ parallel: getTerserParallel(),
28
+ terserOptions: {
29
+ parse: {
30
+ // We want uglify-js to parse ecma 8 code. However, we don't want it
31
+ // to apply any minification steps that turns valid ecma 5 code
32
+ // into invalid ecma 5 code. This is why the 'compress' and 'output'
33
+ // sections only apply transformations that are ecma 5 safe
34
+ // https://github.com/facebook/create-react-app/pull/4234
35
+ ecma: 2020,
36
+ },
37
+ compress: {
38
+ ecma: 5,
39
+ },
40
+ mangle: {
41
+ safari10: true,
42
+ },
43
+ output: {
44
+ ecma: 5,
45
+ comments: false,
46
+ // Turned on because emoji and regex is not minified properly using
47
+ // default. See https://github.com/facebook/create-react-app/issues/2488
48
+ ascii_only: true,
49
+ },
50
+ },
51
+ });
52
+ }
53
+ function getAdvancedCssMinifier() {
54
+ // Using the array syntax to add 2 minimizers
55
+ // see https://github.com/webpack-contrib/css-minimizer-webpack-plugin#array
56
+ return new css_minimizer_webpack_plugin_1.default({
57
+ minimizerOptions: [
58
+ // CssNano options
59
+ {
60
+ preset: require.resolve('@docusaurus/cssnano-preset'),
61
+ },
62
+ // CleanCss options
63
+ {
64
+ inline: false,
65
+ level: {
66
+ 1: {
67
+ all: false,
68
+ removeWhitespace: true,
69
+ },
70
+ 2: {
71
+ all: true,
72
+ restructureRules: true,
73
+ removeUnusedAtRules: false,
74
+ },
75
+ },
76
+ },
77
+ ],
78
+ minify: [
79
+ css_minimizer_webpack_plugin_1.default.cssnanoMinify,
80
+ css_minimizer_webpack_plugin_1.default.cleanCssMinify,
81
+ ],
82
+ });
83
+ }
84
+ function getMinimizer() {
85
+ // This is an historical env variable to opt-out of the advanced minifier
86
+ // Sometimes there's a bug in it and people are happy to disable it
87
+ const useSimpleCssMinifier = process.env.USE_SIMPLE_CSS_MINIFIER === 'true';
88
+ const minimizer = [getJsMinifierPlugin()];
89
+ if (useSimpleCssMinifier) {
90
+ minimizer.push(new css_minimizer_webpack_plugin_1.default());
91
+ }
92
+ else {
93
+ minimizer.push(getAdvancedCssMinifier());
94
+ }
95
+ return minimizer;
96
+ }
97
+ exports.getMinimizer = getMinimizer;
@@ -4,9 +4,11 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- import { type Locals } from '@slorber/static-site-generator-webpack-plugin';
8
7
  import type { Props } from '@docusaurus/types';
9
8
  import type { Configuration } from 'webpack';
10
- export default function createServerConfig({ props, onLinksCollected, onHeadTagsCollected, }: Pick<Locals, 'onLinksCollected' | 'onHeadTagsCollected'> & {
9
+ export default function createServerConfig(params: {
11
10
  props: Props;
12
- }): Promise<Configuration>;
11
+ }): Promise<{
12
+ config: Configuration;
13
+ serverBundlePath: string;
14
+ }>;
@@ -8,76 +8,67 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const tslib_1 = require("tslib");
10
10
  const path_1 = tslib_1.__importDefault(require("path"));
11
+ const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
11
12
  const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
12
13
  const utils_1 = require("@docusaurus/utils");
13
- // Forked for Docusaurus: https://github.com/slorber/static-site-generator-webpack-plugin
14
- const static_site_generator_webpack_plugin_1 = tslib_1.__importDefault(require("@slorber/static-site-generator-webpack-plugin"));
15
14
  const webpackbar_1 = tslib_1.__importDefault(require("webpackbar"));
15
+ const copy_webpack_plugin_1 = tslib_1.__importDefault(require("copy-webpack-plugin"));
16
16
  const base_1 = require("./base");
17
- const WaitPlugin_1 = tslib_1.__importDefault(require("./plugins/WaitPlugin"));
18
- const ssr_html_template_1 = tslib_1.__importDefault(require("./templates/ssr.html.template"));
19
- async function createServerConfig({ props, onLinksCollected, onHeadTagsCollected, }) {
20
- const { baseUrl, routesPaths, generatedFilesDir, headTags, preBodyTags, postBodyTags, siteConfig: { noIndex, trailingSlash, ssrTemplate }, } = props;
21
- const config = await (0, base_1.createBaseConfig)(props, true);
22
- const routesLocation = {};
23
- // Array of paths to be rendered. Relative to output directory
24
- const ssgPaths = routesPaths.map((str) => {
25
- const ssgPath = baseUrl === '/' ? str : str.replace(new RegExp(`^${baseUrl}`), '/');
26
- routesLocation[ssgPath] = str;
27
- return ssgPath;
17
+ async function createServerConfig(params) {
18
+ const { props } = params;
19
+ const baseConfig = await (0, base_1.createBaseConfig)({
20
+ props,
21
+ isServer: true,
22
+ // Minification of server bundle reduces size but doubles bundle time :/
23
+ minify: false,
28
24
  });
29
- const serverConfig = (0, webpack_merge_1.default)(config, {
25
+ const outputFilename = 'server.bundle.js';
26
+ const serverBundlePath = path_1.default.join(props.outDir, outputFilename);
27
+ const config = (0, webpack_merge_1.default)(baseConfig, {
30
28
  target: `node${utils_1.NODE_MAJOR_VERSION}.${utils_1.NODE_MINOR_VERSION}`,
31
29
  entry: {
32
30
  main: path_1.default.resolve(__dirname, '../client/serverEntry.js'),
33
31
  },
34
32
  output: {
35
- filename: 'server.bundle.js',
33
+ filename: outputFilename,
36
34
  libraryTarget: 'commonjs2',
37
35
  // Workaround for Webpack 4 Bug (https://github.com/webpack/webpack/issues/6522)
38
36
  globalObject: 'this',
39
37
  },
40
38
  plugins: [
41
- // Wait until manifest from client bundle is generated
42
- new WaitPlugin_1.default({
43
- filepath: path_1.default.join(generatedFilesDir, 'client-manifest.json'),
44
- }),
45
- // Static site generator webpack plugin.
46
- new static_site_generator_webpack_plugin_1.default({
47
- entry: 'main',
48
- locals: {
49
- baseUrl,
50
- generatedFilesDir,
51
- routesLocation,
52
- headTags,
53
- preBodyTags,
54
- postBodyTags,
55
- onLinksCollected,
56
- onHeadTagsCollected,
57
- ssrTemplate: ssrTemplate ?? ssr_html_template_1.default,
58
- noIndex,
59
- DOCUSAURUS_VERSION: utils_1.DOCUSAURUS_VERSION,
60
- },
61
- paths: ssgPaths,
62
- preferFoldersOutput: trailingSlash,
63
- // When using "new URL('file.js', import.meta.url)", Webpack will emit
64
- // __filename, and this plugin will throw. not sure the __filename value
65
- // has any importance for this plugin, just using an empty string to
66
- // avoid the error. See https://github.com/facebook/docusaurus/issues/4922
67
- globals: { __filename: '' },
68
- // Secret way to set SSR plugin concurrency option
69
- // Waiting for feedback before documenting this officially?
70
- concurrency: process.env.DOCUSAURUS_SSR_CONCURRENCY
71
- ? parseInt(process.env.DOCUSAURUS_SSR_CONCURRENCY, 10)
72
- : undefined,
73
- }),
74
39
  // Show compilation progress bar.
75
40
  new webpackbar_1.default({
76
41
  name: 'Server',
77
42
  color: 'yellow',
78
43
  }),
79
- ],
44
+ await createStaticDirectoriesCopyPlugin(params),
45
+ ].filter(Boolean),
80
46
  });
81
- return serverConfig;
47
+ return { config, serverBundlePath };
82
48
  }
83
49
  exports.default = createServerConfig;
50
+ async function createStaticDirectoriesCopyPlugin({ props }) {
51
+ const { outDir, siteDir, siteConfig: { staticDirectories: staticDirectoriesOption }, } = props;
52
+ // The staticDirectories option can contain empty directories, or non-existent
53
+ // directories (e.g. user deleted `static`). Instead of issuing an error, we
54
+ // just silently filter them out, because user could have never configured it
55
+ // in the first place (the default option should always "work").
56
+ const staticDirectories = (await Promise.all(staticDirectoriesOption.map(async (dir) => {
57
+ const staticDir = path_1.default.resolve(siteDir, dir);
58
+ if ((await fs_extra_1.default.pathExists(staticDir)) &&
59
+ (await fs_extra_1.default.readdir(staticDir)).length > 0) {
60
+ return staticDir;
61
+ }
62
+ return '';
63
+ }))).filter(Boolean);
64
+ if (staticDirectories.length === 0) {
65
+ return undefined;
66
+ }
67
+ return new copy_webpack_plugin_1.default({
68
+ patterns: staticDirectories.map((dir) => ({
69
+ from: dir,
70
+ to: outDir,
71
+ toType: 'dir',
72
+ })),
73
+ });
74
+ }
@@ -5,9 +5,9 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  /// <reference types="node" />
8
- import webpack, { type Configuration, type RuleSetRule, type WebpackPluginInstance } from 'webpack';
8
+ import webpack, { type Configuration, type RuleSetRule } from 'webpack';
9
9
  import type { TransformOptions } from '@babel/core';
10
- import type { Plugin } from '@docusaurus/types';
10
+ import type { Plugin, LoadedPlugin } from '@docusaurus/types';
11
11
  export declare function formatStatsErrorMessage(statsJson: ReturnType<webpack.Stats['toJson']> | undefined): string | undefined;
12
12
  export declare function printStatsWarnings(statsJson: ReturnType<webpack.Stats['toJson']> | undefined): void;
13
13
  export declare function getStyleLoaders(isServer: boolean, cssOptionsArg?: {
@@ -33,15 +33,24 @@ export declare const getCustomizableJSLoader: (jsLoader?: "babel" | ((isServer:
33
33
  */
34
34
  export declare function applyConfigureWebpack(configureWebpack: NonNullable<Plugin['configureWebpack']>, config: Configuration, isServer: boolean, jsLoader: 'babel' | ((isServer: boolean) => RuleSetRule) | undefined, content: unknown): Configuration;
35
35
  export declare function applyConfigurePostCss(configurePostCss: NonNullable<Plugin['configurePostCss']>, config: Configuration): Configuration;
36
+ export declare function executePluginsConfigurePostCss({ plugins, config, }: {
37
+ plugins: LoadedPlugin[];
38
+ config: Configuration;
39
+ }): Configuration;
40
+ export declare function executePluginsConfigureWebpack({ plugins, config, isServer, jsLoader, }: {
41
+ plugins: LoadedPlugin[];
42
+ config: Configuration;
43
+ isServer: boolean;
44
+ jsLoader: 'babel' | ((isServer: boolean) => RuleSetRule) | undefined;
45
+ }): Configuration;
36
46
  declare global {
37
47
  interface Error {
38
48
  /** @see https://webpack.js.org/api/node/#error-handling */
39
49
  details: unknown;
40
50
  }
41
51
  }
42
- export declare function compile(config: Configuration[]): Promise<void>;
52
+ export declare function compile(config: Configuration[]): Promise<webpack.MultiStats>;
43
53
  export declare function getHttpsConfig(): Promise<boolean | {
44
54
  cert: Buffer;
45
55
  key: Buffer;
46
56
  }>;
47
- export declare function getMinimizer(useSimpleCssMinifier?: boolean): WebpackPluginInstance[];