Skip to content

Commit

Permalink
perf(cli): lazy import rechoir and interpret
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan committed Dec 26, 2024
1 parent 7707956 commit 7a6f7a4
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions packages/rspack-cli/src/utils/loadConfig.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import type { MultiRspackOptions, RspackOptions } from "@rspack/core";
import interpret from "interpret";
import rechoir from "rechoir";

import type { RspackCLIOptions } from "../types";
import crossImport from "./crossImport";
import crossImport, { dynamicImport } from "./crossImport";
import findConfig from "./findConfig";
import isEsmFile from "./isEsmFile";
import isTsFile from "./isTsFile";
Expand All @@ -17,20 +14,24 @@ interface RechoirError extends Error {

const DEFAULT_CONFIG_NAME = "rspack.config" as const;

const registerLoader = (configPath: string) => {
const registerLoader = async (configPath: string) => {
const ext = path.extname(configPath);
// TODO implement good `.mts` support after https://github.com/gulpjs/rechoir/issues/43
// For ESM and `.mts` you need to use: 'NODE_OPTIONS="--loader ts-node/esm" rspack build --config ./rspack.config.mts'
if (isEsmFile(configPath) && isTsFile(configPath)) {
return;
}

const { default: interpret } = await dynamicImport("interpret");
const extensions = Object.fromEntries(
Object.entries(interpret.extensions).filter(([key]) => key === ext)
);
if (Object.keys(extensions).length === 0) {
throw new Error(`config file "${configPath}" is not supported.`);
}

try {
const { default: rechoir } = await dynamicImport("rechoir");
rechoir.prepare(extensions, configPath);
} catch (error) {
const failures = (error as RechoirError)?.failures;
Expand Down Expand Up @@ -60,12 +61,17 @@ export async function loadRspackConfig(
if (!fs.existsSync(configPath)) {
throw new Error(`config file "${configPath}" not found.`);
}
isTsFile(configPath) && registerLoader(configPath);
if (isTsFile(configPath)) {
await registerLoader(configPath);
}
return crossImport(configPath, cwd);
}

const defaultConfig = findConfig(path.resolve(cwd, DEFAULT_CONFIG_NAME));
if (defaultConfig) {
isTsFile(defaultConfig) && registerLoader(defaultConfig);
if (isTsFile(defaultConfig)) {
await registerLoader(defaultConfig);
}
return crossImport(defaultConfig, cwd);
}
return {};
Expand Down

0 comments on commit 7a6f7a4

Please sign in to comment.