Skip to content

Commit

Permalink
fix(types): add standalone types for node require (#316)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Oct 3, 2024
1 parent e7ffe04 commit b3a4ccb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 16 deletions.
65 changes: 50 additions & 15 deletions lib/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,7 @@ export declare function createJiti(id: string, userOptions?: JitiOptions): Jiti;
*
* **Note:**It is recommended to use `await jiti.import` instead
*/
export interface Jiti {
/** @deprecated Prefer `await jiti.import()` for better compatibility. */
(id: string): any;

/** @deprecated Prefer `jiti.esmResolve` for better compatibility. */
resolve: RequireResolve;

/** @deprecated */
extensions: RequireExtensions;

/** @deprecated CommonJS API */
main: Module | undefined;

cache: Dict<NodeModule>;

export interface Jiti extends NodeRequire {
/**
* Resolved options
*/
Expand Down Expand Up @@ -175,6 +161,55 @@ export interface JitiOptions {
jsx?: boolean | JSXOptions;
}

interface NodeRequire {
/**
* Module cache
*/
cache: ModuleCache;

/** @deprecated Prefer `await jiti.import()` for better compatibility. */
(id: string): any;

/** @deprecated Prefer `jiti.esmResolve` for better compatibility. */
resolve: {
/** @deprecated */
(id: string, options?: { paths?: string[] | undefined }): string;
/** @deprecated */
paths(request: string): string[] | null;
};

/** @deprecated CommonJS API */
extensions: Record<
".js" | ".json" | ".node",
(m: Module, filename: string) => any | undefined
>;

/** @deprecated CommonJS API */
main: Module | undefined;
}

export interface NodeModule {
/**
* `true` if the module is running during the Node.js preload
*/
isPreloading: boolean;
exports: any;
require: NodeRequire;
id: string;
filename: string;
loaded: boolean;
/** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */
parent: NodeModule | null | undefined;
children: NodeModule[];
/**
* @since v11.14.0
*
* The directory name of the module. This is usually the same as the path.dirname() of the module.id.
*/
path: string;
paths: string[];
}

export type ModuleCache = Record<string, NodeModule>;

export type EvalModuleOptions = Partial<{
Expand Down
2 changes: 1 addition & 1 deletion src/eval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export function evalModule(
mod.paths = Module._nodeModulePaths(mod.path);

// Set CJS cache before eval
cache[filename] = mod;
cache[filename] = mod as ModuleCache[string];
if (ctx.opts.moduleCache) {
ctx.nativeRequire.cache[filename] = mod;
}
Expand Down

0 comments on commit b3a4ccb

Please sign in to comment.