/
start.ts
251 lines (225 loc) · 7.28 KB
/
start.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
/**
* 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 path from 'path';
import _ from 'lodash';
import logger from '@docusaurus/logger';
import {normalizeUrl, posixPath} from '@docusaurus/utils';
import chokidar from 'chokidar';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import openBrowser from 'react-dev-utils/openBrowser';
import {prepareUrls} from 'react-dev-utils/WebpackDevServerUtils';
import evalSourceMapMiddleware from 'react-dev-utils/evalSourceMapMiddleware';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import merge from 'webpack-merge';
import {load, type LoadContextOptions} from '../server';
import createClientConfig from '../webpack/client';
import {
applyConfigureWebpack,
applyConfigurePostCss,
getHttpsConfig,
} from '../webpack/utils';
import {getHostPort, type HostPortOptions} from '../server/getHostPort';
export type StartCLIOptions = HostPortOptions &
Pick<LoadContextOptions, 'locale' | 'config'> & {
hotOnly?: boolean;
open?: boolean;
poll?: boolean | number;
minify?: boolean;
};
export async function start(
siteDirParam: string = '.',
cliOptions: Partial<StartCLIOptions> = {},
): Promise<void> {
const siteDir = await fs.realpath(siteDirParam);
process.env.NODE_ENV = 'development';
process.env.BABEL_ENV = 'development';
logger.info('Starting the development server...');
function loadSite() {
return load({
siteDir,
config: cliOptions.config,
locale: cliOptions.locale,
localizePath: undefined, // Should this be configurable?
});
}
// Process all related files as a prop.
const props = await loadSite();
const protocol: string = process.env.HTTPS === 'true' ? 'https' : 'http';
const {host, port} = await getHostPort(cliOptions);
if (port === null) {
process.exit();
}
const {baseUrl, headTags, preBodyTags, postBodyTags} = props;
const urls = prepareUrls(protocol, host, port);
const openUrl = normalizeUrl([urls.localUrlForBrowser, baseUrl]);
logger.success`Docusaurus website is running at: url=${openUrl}`;
// Reload files processing.
const reload = _.debounce(() => {
loadSite()
.then(({baseUrl: newBaseUrl}) => {
const newOpenUrl = normalizeUrl([urls.localUrlForBrowser, newBaseUrl]);
if (newOpenUrl !== openUrl) {
logger.success`Docusaurus website is running at: url=${newOpenUrl}`;
}
})
.catch((err: Error) => {
logger.error(err.stack);
});
}, 500);
const {siteConfig, plugins, localizationDir} = props;
const normalizeToSiteDir = (filepath: string) => {
if (filepath && path.isAbsolute(filepath)) {
return posixPath(path.relative(siteDir, filepath));
}
return posixPath(filepath);
};
const pluginPaths = plugins
.flatMap((plugin) => plugin.getPathsToWatch?.() ?? [])
.filter(Boolean)
.map(normalizeToSiteDir);
const pathsToWatch = [...pluginPaths, props.siteConfigPath, localizationDir];
const pollingOptions = {
usePolling: !!cliOptions.poll,
interval: Number.isInteger(cliOptions.poll)
? (cliOptions.poll as number)
: undefined,
};
const httpsConfig = await getHttpsConfig();
const fsWatcher = chokidar.watch(pathsToWatch, {
cwd: siteDir,
ignoreInitial: true,
...{pollingOptions},
});
['add', 'change', 'unlink', 'addDir', 'unlinkDir'].forEach((event) =>
fsWatcher.on(event, reload),
);
let config: webpack.Configuration = merge(
await createClientConfig(props, cliOptions.minify),
{
watchOptions: {
ignored: /node_modules\/(?!@docusaurus)/,
poll: cliOptions.poll,
},
infrastructureLogging: {
// Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
level: 'warn',
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
template: path.join(
__dirname,
'../webpack/templates/index.html.template.ejs',
),
// So we can define the position where the scripts are injected.
inject: false,
filename: 'index.html',
title: siteConfig.title,
headTags,
preBodyTags,
postBodyTags,
}),
],
},
);
// Plugin Lifecycle - configureWebpack and configurePostCss.
plugins.forEach((plugin) => {
const {configureWebpack, configurePostCss} = plugin;
if (configurePostCss) {
config = applyConfigurePostCss(configurePostCss.bind(plugin), config);
}
if (configureWebpack) {
config = applyConfigureWebpack(
configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
config,
false,
props.siteConfig.webpack?.jsLoader,
plugin.content,
);
}
});
const compiler = webpack(config);
if (process.env.E2E_TEST) {
compiler.hooks.done.tap('done', (stats) => {
if (stats.hasErrors()) {
logger.error('E2E_TEST: Project has compiler errors.');
process.exit(1);
}
logger.success('E2E_TEST: Project can compile.');
process.exit(0);
});
}
// https://webpack.js.org/configuration/dev-server
const defaultDevServerConfig: WebpackDevServer.Configuration = {
hot: cliOptions.hotOnly ? 'only' : true,
liveReload: false,
client: {
progress: true,
overlay: {
warnings: false,
errors: true,
},
},
headers: {
'access-control-allow-origin': '*',
},
devMiddleware: {
publicPath: baseUrl,
// Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
stats: 'summary',
},
static: siteConfig.staticDirectories.map((dir) => ({
publicPath: baseUrl,
directory: path.resolve(siteDir, dir),
watch: {
// Useful options for our own monorepo using symlinks!
// See https://github.com/webpack/webpack/issues/11612#issuecomment-879259806
followSymlinks: true,
ignored: /node_modules\/(?!@docusaurus)/,
...{pollingOptions},
},
})),
...(httpsConfig && {
server:
typeof httpsConfig === 'object'
? {
type: 'https',
options: httpsConfig,
}
: 'https',
}),
historyApiFallback: {
rewrites: [{from: /\/*/, to: baseUrl}],
},
allowedHosts: 'all',
host,
port,
setupMiddlewares: (middlewares, devServer) => {
// This lets us fetch source contents from webpack for the error overlay.
middlewares.unshift(evalSourceMapMiddleware(devServer));
return middlewares;
},
};
// Allow plugin authors to customize/override devServer config
const devServerConfig: WebpackDevServer.Configuration = merge(
[defaultDevServerConfig, config.devServer].filter(Boolean),
);
const devServer = new WebpackDevServer(devServerConfig, compiler);
devServer.startCallback(() => {
if (cliOptions.open) {
openBrowser(openUrl);
}
});
['SIGINT', 'SIGTERM'].forEach((sig) => {
process.on(sig, () => {
devServer.stop();
process.exit();
});
});
}