Skip to content

Commit

Permalink
refactor(core): convert serverEntry.js to TS (#6237)
Browse files Browse the repository at this point in the history
* refactor(core): convert serverEntry.js to TS

* fix

* migrate template to TS

* Move templates
  • Loading branch information
Josh-Cena authored Jan 5, 2022
1 parent e86fd23 commit 37b70e3
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 33 deletions.
2 changes: 1 addition & 1 deletion packages/docusaurus-types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ export interface LoadContext {
outDir: string;
baseUrl: string; // TODO to remove: useless, there's already siteConfig.baseUrl!
i18n: I18n;
ssrTemplate?: string;
ssrTemplate: string;
codeTranslations: Record<string, string>;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,18 @@
* LICENSE file in the root directory of this source tree.
*/

// @ts-check

import * as eta from 'eta';
import React from 'react';
import {StaticRouter} from 'react-router-dom';
import ReactDOMServer from 'react-dom/server';
import {Helmet} from 'react-helmet';
import {getBundles} from 'react-loadable-ssr-addon-v5-slorber';
import {getBundles, type Manifest} from 'react-loadable-ssr-addon-v5-slorber';
import Loadable from 'react-loadable';

import {minify} from 'html-minifier-terser';
import path from 'path';
import fs from 'fs-extra';
import routes from '@generated/routes';
import packageJson from '../../package.json';
import preload from './preload';
import App from './App';
import {
Expand All @@ -29,29 +26,37 @@ import {
import logger from '@docusaurus/logger';
// eslint-disable-next-line no-restricted-imports
import {memoize} from 'lodash';
import type {Locals} from '@slorber/static-site-generator-webpack-plugin';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJson = require('../../package.json');

const getCompiledSSRTemplate = memoize((template) =>
const getCompiledSSRTemplate = memoize((template: string) =>
eta.compile(template.trim(), {
rmWhitespace: true,
}),
);

function renderSSRTemplate(ssrTemplate, data) {
function renderSSRTemplate(ssrTemplate: string, data: object) {
const compiled = getCompiledSSRTemplate(ssrTemplate);
return compiled(data, eta.defaultConfig);
}

export default async function render(locals) {
export default async function render(
locals: Locals & {path: string},
): Promise<string> {
try {
return await doRender(locals);
} catch (e) {
logger.error`Docusaurus Node/SSR could not render static page with path path=${locals.path} because of following error:
${e.stack}`;
logger.error`Docusaurus Node/SSR could not render static page with path path=${
locals.path
} because of following error:
${(e as Error).stack!}`;

const isNotDefinedErrorRegex =
/(window|document|localStorage|navigator|alert|location|buffer|self) is not defined/i;

if (isNotDefinedErrorRegex.test(e.message)) {
if (isNotDefinedErrorRegex.test((e as Error).message)) {
logger.info`It looks like you are using code that should run on the client-side only.
To get around it, try using code=${'<BrowserOnly>'} (path=${'https://docusaurus.io/docs/docusaurus-core/#browseronly'}) or code=${'ExecutionEnvironment'} (path=${'https://docusaurus.io/docs/docusaurus-core/#executionenvironment'}).
It might also require to wrap your client code in code=${'useEffect'} hook and/or import a third-party library dynamically (if any).`;
Expand All @@ -62,7 +67,7 @@ It might also require to wrap your client code in code=${'useEffect'} hook and/o
}

// Renderer for static-site-generator-webpack-plugin (async rendering via promises).
async function doRender(locals) {
async function doRender(locals: Locals & {path: string}) {
const {
routesLocation,
headTags,
Expand All @@ -75,7 +80,7 @@ async function doRender(locals) {
} = locals;
const location = routesLocation[locals.path];
await preload(routes, location);
const modules = new Set();
const modules = new Set<string>();
const context = {};

const linksCollector = createStatefulLinksCollector();
Expand Down Expand Up @@ -103,7 +108,9 @@ async function doRender(locals) {

const {generatedFilesDir} = locals;
const manifestPath = path.join(generatedFilesDir, 'client-manifest.json');
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
const manifest: Manifest = JSON.parse(
await fs.readFile(manifestPath, 'utf8'),
);

// Get all required assets for this particular page based on client
// manifest information.
Expand Down Expand Up @@ -139,8 +146,10 @@ async function doRender(locals) {
minifyJS: true,
});
} catch (e) {
logger.error`Minification of page path=${locals.path} failed because of following error:
${e.stack}`;
logger.error`Minification of page path=${
locals.path
} failed because of following error:
${(e as Error).stack!}`;
throw e;
}
}

This file was deleted.

2 changes: 1 addition & 1 deletion packages/docusaurus/src/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export default async function start(
new HtmlWebpackPlugin({
template: path.resolve(
__dirname,
'../client/templates/index.html.template.ejs',
'../webpack/templates/index.html.template.ejs',
),
// So we can define the position where the scripts are injected.
inject: false,
Expand Down
54 changes: 52 additions & 2 deletions packages/docusaurus/src/deps.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,63 @@

declare module 'remark-admonitions';

declare module 'react-loadable-ssr-addon-v5-slorber';
declare module 'react-loadable-ssr-addon-v5-slorber' {
type Asset = {
file: string;
hash: string;
publicPath: string;
integrity: string;
};

export type Manifest = {
entrypoints: string[];
origins: Record<string, number[]>;
assets: Array<Record<string, Asset[]>>;
};

export function getBundles(
manifest: Manifest,
modulesToBeLoaded: string[],
): {js: Asset[]; css: Asset[]};

interface ReactLoadableSSRAddon {
new (props: {filename: string});
}

declare const plugin: ReactLoadableSSRAddon;
export default plugin;
}

declare module 'resolve-pathname' {
export default function resolvePathname(to: string, from?: string): string;
}

declare module '@slorber/static-site-generator-webpack-plugin';
declare module '@slorber/static-site-generator-webpack-plugin' {
export type Locals = {
routesLocation: Record<string, string>;
generatedFilesDir: string;
headTags: string;
preBodyTags: string;
postBodyTags: string;
onLinksCollected: (staticPagePath: string, links: string[]) => void;
baseUrl: string;
ssrTemplate: string;
noIndex: boolean;
};

interface StaticSiteGeneratorPlugin {
new (props: {
entry: string;
locals: Locals;
paths: string[];
preferFoldersOutput?: boolean;
globals: Record<string, unknown>;
});
}

declare const plugin: StaticSiteGeneratorPlugin;
export default plugin;
}

declare module 'webpack/lib/HotModuleReplacementPlugin' {
import {HotModuleReplacementPlugin} from 'webpack';
Expand Down
6 changes: 3 additions & 3 deletions packages/docusaurus/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from '@docusaurus/utils';
import path from 'path';
import logger from '@docusaurus/logger';
import ssrDefaultTemplate from '../client/templates/ssr.html.template';
import ssrDefaultTemplate from '../webpack/templates/ssr.html.template';
import loadClientModules from './client-modules';
import loadConfig from './config';
import {loadPlugins} from './plugins';
Expand Down Expand Up @@ -124,7 +124,7 @@ export async function loadContext(
outDir,
baseUrl, // TODO to remove: useless, there's already siteConfig.baseUrl! (and yes, it's the same value, cf code above)
i18n,
ssrTemplate,
ssrTemplate: ssrTemplate ?? ssrDefaultTemplate,
codeTranslations,
};
}
Expand Down Expand Up @@ -428,7 +428,7 @@ ${Object.keys(registry)
headTags,
preBodyTags,
postBodyTags,
ssrTemplate: ssrTemplate || ssrDefaultTemplate,
ssrTemplate,
codeTranslations,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

module.exports = `
export default `
<!DOCTYPE html>
<html <%~ it.htmlAttributes %>>
<head>
Expand Down
3 changes: 2 additions & 1 deletion packages/docusaurus/tsconfig.client.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
"lib": ["DOM", "ES2019"],
"module": "esnext",
"tsBuildInfoFile": "./lib/client/.tsbuildinfo",
"rootDir": "src/client",
"outDir": "lib/client",
"jsx": "react"
},
"include": ["src/client"]
"include": ["src/client", "src/deps.d.ts"]
}

0 comments on commit 37b70e3

Please sign in to comment.