fix(v2): Resolve plugins relative to siteDir (#2789)

This commit is contained in:
Sam Zhou 2020-05-22 05:04:40 -04:00 committed by GitHub
parent a7925f28be
commit faf48e9b16
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import Module from 'module';
import importFresh from 'import-fresh';
import {LoadContext, Plugin, PluginConfig} from '@docusaurus/types';
@ -15,9 +16,16 @@ export function initPlugins({
pluginConfigs: PluginConfig[];
context: LoadContext;
}): Plugin<any>[] {
// We need to resolve plugins from the perspective of the siteDir, since the siteDir's package.json
// declares the dependency on these plugins.
// We need to fallback to createRequireFromPath since createRequire is only available in node v12.
// See: https://nodejs.org/api/modules.html#modules_module_createrequire_filename
const createRequire = Module.createRequire || Module.createRequireFromPath;
const pluginRequire = createRequire(context.siteDir);
const plugins: Plugin<any>[] = pluginConfigs
.map((pluginItem) => {
let pluginModuleImport;
let pluginModuleImport: string | undefined;
let pluginOptions = {};
if (!pluginItem) {
@ -37,7 +45,9 @@ export function initPlugins({
// The pluginModuleImport value is any valid
// module identifier - npm package or locally-resolved path.
const pluginModule: any = importFresh(pluginModuleImport);
const pluginModule: any = importFresh(
pluginRequire.resolve(pluginModuleImport),
);
return (pluginModule.default || pluginModule)(context, pluginOptions);
})
.filter(Boolean);