Skip to content

Commit

Permalink
refactor(v2): stronger typing for route gen
Browse files Browse the repository at this point in the history
  • Loading branch information
endiliey committed Nov 24, 2019
1 parent e15ab76 commit d353295
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 18 deletions.
4 changes: 4 additions & 0 deletions packages/docusaurus-types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ export interface RouteModule {
[module: string]: Module | RouteModule | RouteModule[];
}

export interface ChunkNames {
[name: string]: string | null | ChunkNames | ChunkNames[];
}

export interface RouteConfig {
path: string;
component: string;
Expand Down
49 changes: 31 additions & 18 deletions packages/docusaurus/src/server/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,23 @@ import {
Module,
RouteConfig,
RouteModule,
ChunkNames,
} from '@docusaurus/types';

function isModule(value: any): value is Module {
if (_.isString(value)) {
return true;
}
if (
_.isPlainObject(value) &&
_.has(value, '__import') &&
_.has(value, 'path')
) {
return true;
}
return false;
}

function getModulePath(target: Module): string {
if (typeof target === 'string') {
return target;
Expand All @@ -33,7 +48,7 @@ export async function loadRoutes(pluginsRouteConfigs: RouteConfig[]) {
} = {};
const routesPaths: string[] = ['404.html'];
const routesChunkNames: {
[routePath: string]: any;
[routePath: string]: ChunkNames;
} = {};

// This is the higher level overview of route code generation
Expand Down Expand Up @@ -73,25 +88,23 @@ export async function loadRoutes(pluginsRouteConfigs: RouteConfig[]) {
);
}

if (_.isPlainObject(value) && !_.isString(value) && !value.__import) {
const newValue = {};
Object.keys(value).forEach(key => {
newValue[key] = genRouteChunkNames(value[key], key, name);
});
return newValue;
if (isModule(value)) {
const modulePath = getModulePath(value);
const chunkName = genChunkName(modulePath, prefix, name);
const loader = `() => import(/* webpackChunkName: '${chunkName}' */ "${modulePath}")`;

registry[chunkName] = {
loader,
modulePath,
};
return chunkName;
}

const modulePath = getModulePath(value as Module);
const chunkName = genChunkName(modulePath, prefix, name);
const loader = `() => import(/* webpackChunkName: '${chunkName}' */ ${JSON.stringify(
modulePath,
)})`;

registry[chunkName] = {
loader,
modulePath,
};
return chunkName;
const newValue: ChunkNames = {};
Object.keys(value).forEach(key => {
newValue[key] = genRouteChunkNames(value[key], key, name);
});
return newValue;
}

routesChunkNames[routePath] = _.assign(
Expand Down

0 comments on commit d353295

Please sign in to comment.