/
start.ts
240 lines (215 loc) · 6.85 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
/**
* 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 {normalizeUrl, posixPath} from '@docusaurus/utils';
import chalk = require('chalk');
import chokidar from 'chokidar';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';
import {debounce} from 'lodash';
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} from '../server';
import {StartCLIOptions} from '@docusaurus/types';
import {STATIC_DIR_NAME} from '../constants';
import createClientConfig from '../webpack/client';
import {
applyConfigureWebpack,
applyConfigurePostCss,
getHttpsConfig,
} from '../webpack/utils';
import {getCLIOptionHost, getCLIOptionPort} from './commandUtils';
import {getTranslationsLocaleDirPath} from '../server/translations/translations';
export default async function start(
siteDir: string,
cliOptions: Partial<StartCLIOptions>,
): Promise<void> {
process.env.NODE_ENV = 'development';
process.env.BABEL_ENV = 'development';
console.log(chalk.blue('Starting the development server...'));
function loadSite() {
return load(siteDir, {
customConfigFilePath: 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: string = getCLIOptionHost(cliOptions.host);
const port: number | null = await getCLIOptionPort(cliOptions.port, host);
if (port === null) {
process.exit();
}
const {baseUrl, headTags, preBodyTags, postBodyTags} = props;
const urls = prepareUrls(protocol, host, port);
const openUrl = normalizeUrl([urls.localUrlForBrowser, baseUrl]);
console.log(
chalk.cyanBright(`Docusaurus website is running at "${openUrl}".`),
);
// Reload files processing.
const reload = debounce(() => {
loadSite()
.then(({baseUrl: newBaseUrl}) => {
const newOpenUrl = normalizeUrl([urls.localUrlForBrowser, newBaseUrl]);
if (newOpenUrl !== openUrl) {
console.log(
chalk.cyanBright(
`Docusaurus website is running at "${newOpenUrl}".`,
),
);
}
})
.catch((err) => {
console.error(chalk.red(err.stack));
});
}, 500);
const {siteConfig, plugins = []} = props;
const normalizeToSiteDir = (filepath: string) => {
if (filepath && path.isAbsolute(filepath)) {
return posixPath(path.relative(siteDir, filepath));
}
return posixPath(filepath);
};
const pluginPaths = ([] as string[])
.concat(
...plugins
.map((plugin) => plugin.getPathsToWatch?.() ?? [])
.filter(Boolean),
)
.map(normalizeToSiteDir);
const pathsToWatch = [
...pluginPaths,
props.siteConfigPath,
getTranslationsLocaleDirPath({
siteDir,
locale: props.i18n.currentLocale,
}),
];
const fsWatcher = chokidar.watch(pathsToWatch, {
cwd: siteDir,
ignoreInitial: true,
usePolling: !!cliOptions.poll,
interval: Number.isInteger(cliOptions.poll)
? (cliOptions.poll as number)
: undefined,
});
['add', 'change', 'unlink', 'addDir', 'unlinkDir'].forEach((event) =>
fsWatcher.on(event, reload),
);
let config: webpack.Configuration = merge(createClientConfig(props), {
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.resolve(
__dirname,
'../client/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, config);
}
if (configureWebpack) {
config = applyConfigureWebpack(
configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`. // TODO remove this implicit api: inject in callback instead
config,
false,
props.siteConfig.webpack?.jsLoader,
plugin.content,
);
}
});
// https://webpack.js.org/configuration/dev-server
const devServerConfig: WebpackDevServer.Configuration = {
compress: true,
hot: cliOptions.hotOnly ? 'only' : true,
client: {
progress: true,
overlay: {
warnings: false,
errors: true,
},
},
https: getHttpsConfig(),
headers: {
'access-control-allow-origin': '*',
},
devMiddleware: {
publicPath: baseUrl,
// Reduce log verbosity, see https://github.com/facebook/docusaurus/pull/5420#issuecomment-906613105
stats: 'errors-warnings',
},
static: {
directory: path.resolve(siteDir, STATIC_DIR_NAME),
watch: {
usePolling: !!cliOptions.poll,
// Useful options for our own monorepo using symlinks!
// See https://github.com/webpack/webpack/issues/11612#issuecomment-879259806
followSymlinks: true,
ignored: /node_modules\/(?!@docusaurus)/,
},
},
historyApiFallback: {
rewrites: [{from: /\/*/, to: baseUrl}],
},
allowedHosts: 'all',
host,
port,
onBeforeSetupMiddleware: (devServer) => {
// This lets us fetch source contents from webpack for the error overlay.
devServer.app.use(
evalSourceMapMiddleware(
// @ts-expect-error: bad types
devServer,
),
);
},
};
const compiler = webpack(config);
if (process.env.E2E_TEST) {
compiler.hooks.done.tap('done', (stats) => {
if (stats.hasErrors()) {
console.log('E2E_TEST: Project has compiler errors.');
process.exit(1);
}
console.log('E2E_TEST: Project can compile.');
process.exit(0);
});
}
const devServer = new WebpackDevServer(devServerConfig, compiler);
devServer.startCallback(() => {
if (cliOptions.open) {
openBrowser(openUrl);
}
});
['SIGINT', 'SIGTERM'].forEach((sig) => {
process.on(sig, () => {
devServer.close();
process.exit();
});
});
}