When I declare require as per the documentation in a require.d.ts
declare var require: {
<T>(path: string): T;
(paths: string[], callback: (...modules: any[]) => void): void;
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
};
it then clashes with the node.d.ts declare var require: NodeRequire;
error TS2403: Subsequent variable declarations must have the same type.
Variable 'require' must be of type '{ <T>(path: string): T; (paths: string[],
callback: (...modules: any[]) => void): void; ensure: (...', but here has type '
NodeRequire'.
is there a workaround?
You don't need to use a require.d.ts. Just remove it and use the definition in node.d.ts instead.
Thanks James, that works for calls to require('module-name') but throws an error for require.ensure
error TS2339: Property 'ensure' does not exist on type 'NodeRequire'.
I know its not a ts-loader thing specifically but maybe you know the solution?
Change require.d.ts to something like this instead:
interface NodeRequire {
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
}
That will extend the NodeRequire interface defined by node.d.ts to include the ensure definition.
brilliant! thanks for the dig out
Just for completeness - here is with the optional named chunk param:
interface NodeRequire {
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void, name?:string ) => void;
}
i have some problem. and update it will have module name.
interface NodeRequire {
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void, name?: string) => void;
}
How to ensure type safety? Something went wrong for me. I'm getting the error as property 'default' does not exist on type {}. Here my lazy module is exported as export default "Hello" and the consumer is using the below code.
require.ensure([], (require) => {
this.content= require('./lazy').default;
})
Hi @arunsn43,
I'd take a look at this example of lazy loading: https://github.com/TypeStrong/ts-loader/tree/master/test/execution-tests/2.4.1_babel-importCodeSplitting
Thank you @johnnyreilly
The error was on typecasting while using and is resolved by (<any>require('./lazy')).default;
Most helpful comment
Change
require.d.tsto something like this instead:That will extend the
NodeRequireinterface defined bynode.d.tsto include theensuredefinition.