Node utility functions for Docusaurus packages providing URL handling, file operations, Git integration, i18n, Markdown processing, content visibility, and build utilities.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Development and build utilities including webpack integration, module loading, CLI helpers, and output generation. These utilities support the development workflow and build processes for Docusaurus applications.
/**
* Webpack compiler names used in Docusaurus
*/
type WebpackCompilerName = "server" | "client";
/**
* File loader utilities for different file types
*/
type FileLoaderUtils = {
loaders: {
file: (options?: any) => any;
url: (options?: any) => any;
// Additional loader configurations
};
rules: any[];
};loadFreshModuleLoads modules bypassing Node.js require cache, supporting ESM, CJS, JSON, and TypeScript.
/**
* Loads modules bypassing Node.js require cache
* @param modulePath - Path to the module to load
* @returns Promise resolving to the loaded module
* @throws Error with descriptive message if module loading fails
*/
function loadFreshModule(modulePath: string): Promise<unknown>;Usage Examples:
import { loadFreshModule } from "@docusaurus/utils";
try {
// Load a configuration file bypassing cache
const config = await loadFreshModule("./docusaurus.config.js");
console.log("Fresh config loaded:", config);
// Load TypeScript modules
const tsModule = await loadFreshModule("./src/config.ts");
// Load JSON data
const jsonData = await loadFreshModule("./data.json");
// Load ES modules
const esmModule = await loadFreshModule("./module.mjs");
} catch (error) {
console.error("Failed to load module:", error.message);
// Error includes descriptive information about the failure
}generateOutputs files to generated files directory with caching for performance.
/**
* Outputs files to generated files directory with caching for performance
* @param generatedFilesDir - Absolute path to output directory
* @param file - File path relative to generatedFilesDir
* @param content - String content to write
* @param skipCache - Force rewrite without cache (defaults to true in production)
* @returns Promise that resolves when file is written
*/
function generate(
generatedFilesDir: string,
file: string,
content: string,
skipCache?: boolean
): Promise<void>;readOutputHTMLFileReads HTML files from build output directory, handling trailing slash configurations.
/**
* Reads HTML files from build output directory
* @param permalink - URL without base URL
* @param outDir - Full path to output directory
* @param trailingSlash - Site trailing slash config option
* @returns Promise resolving to Buffer containing HTML file content
* @throws Error when HTML file not found
*/
function readOutputHTMLFile(
permalink: string,
outDir: string,
trailingSlash?: boolean
): Promise<Buffer>;Usage Examples:
import { generate, readOutputHTMLFile } from "@docusaurus/utils";
// Generate a file with caching
await generate(
"/path/to/.docusaurus",
"routes.js",
`export default ${JSON.stringify(routes, null, 2)};`,
false // Use cache in development
);
// Generate without caching (force write)
await generate(
"/path/to/.docusaurus",
"client-manifest.json",
JSON.stringify(manifest),
true // Skip cache, always write
);
// Read output HTML file
try {
const htmlBuffer = await readOutputHTMLFile(
"/docs/intro",
"/path/to/build",
true // Site uses trailing slashes
);
const htmlContent = htmlBuffer.toString("utf8");
console.log("HTML content:", htmlContent);
} catch (error) {
console.error("HTML file not found:", error.message);
}getWebpackLoaderCompilerNameExtracts compiler name from webpack loader context.
/**
* Extracts compiler name from webpack loader context
* @param context - Webpack loader context object
* @returns Compiler name ("server" or "client")
*/
function getWebpackLoaderCompilerName(context: LoaderContext<unknown>): WebpackCompilerName;getFileLoaderUtilsReturns unified loader configurations for various file types (images, fonts, media, etc.).
/**
* Returns unified loader configurations for various file types
* @param isServer - Whether this is for server-side rendering
* @returns File loader utilities with configured loaders and rules
*/
function getFileLoaderUtils(isServer: boolean): FileLoaderUtils;Usage Examples:
import { getWebpackLoaderCompilerName, getFileLoaderUtils } from "@docusaurus/utils";
// In a webpack loader
function myWebpackLoader(source) {
const compilerName = getWebpackLoaderCompilerName(this);
if (compilerName === "server") {
// Server-side processing
return processForServer(source);
} else {
// Client-side processing
return processForClient(source);
}
}
// Get file loader configuration
const clientLoaders = getFileLoaderUtils(false); // For client build
const serverLoaders = getFileLoaderUtils(true); // For server build
// Use in webpack config
const webpackConfig = {
module: {
rules: [
...clientLoaders.rules,
{
test: /\.(png|jpg|jpeg|gif)$/,
use: clientLoaders.loaders.url({
limit: 10000,
fallback: clientLoaders.loaders.file(),
}),
},
],
},
};askPreferredLanguageInteractive prompt asking user to choose between JavaScript and TypeScript.
/**
* Interactive prompt asking user to choose between JavaScript and TypeScript
* @param options - Options for the prompt
* @param options.fallback - Default language when no input (optional)
* @param options.exit - Whether to exit process on cancellation (optional)
* @returns Promise resolving to selected language
*/
function askPreferredLanguage(options?: Partial<{
fallback: "javascript" | "typescript" | undefined;
exit: boolean;
}>): Promise<"javascript" | "typescript">;Usage Example:
import { askPreferredLanguage } from "@docusaurus/utils";
async function setupProject() {
try {
const language = await askPreferredLanguage({
fallback: "javascript",
exit: true,
});
console.log(`Selected language: ${language}`);
if (language === "typescript") {
// Setup TypeScript configuration
await setupTypeScript();
} else {
// Setup JavaScript configuration
await setupJavaScript();
}
} catch (error) {
console.error("Language selection cancelled");
process.exit(1);
}
}
// Usage in CLI tools
async function initCommand() {
console.log("Setting up your Docusaurus project...");
const preferredLang = await askPreferredLanguage({
fallback: "javascript",
exit: false,
});
const templateDir = preferredLang === "typescript"
? "template-typescript"
: "template-javascript";
// Continue with project setup using selected language
}import {
loadFreshModule,
generate,
getWebpackLoaderCompilerName
} from "@docusaurus/utils";
// Hot reload configuration files
async function reloadConfig() {
// Always get fresh config, bypassing Node.js cache
const newConfig = await loadFreshModule("./docusaurus.config.js");
return newConfig;
}
// Generate route files during development
async function generateRoutes(routes, outputDir) {
const routeContent = `
export default ${JSON.stringify(routes, null, 2)};
// Auto-generated by Docusaurus
// Do not edit this file manually
`;
await generate(
outputDir,
"routes.js",
routeContent,
process.env.NODE_ENV === "production" // Skip cache in production
);
}
// Custom webpack loader using compiler detection
function docusaurusTransformLoader(source) {
const compiler = getWebpackLoaderCompilerName(this);
// Apply different transformations based on build target
if (compiler === "server") {
return transformForSSR(source);
} else {
return transformForBrowser(source);
}
}Install with Tessl CLI
npx tessl i tessl/npm-docusaurus--utils