vite-plugins
vite-plugins copied to clipboard
vite-plugin-require-context - TypeScript
Is your feature request related to a problem? Please describe.
When I use vite-plugin-require-context
plugin in my app, TypeScript throws an error "Property 'context' does not exist on type 'NodeRequire'."
Describe the solution you'd like
Some d.ts
to use and augment the type system so require.context
is not unknown to TS
Describe alternatives you've considered
I'v of course tried to augment NodeRequire interface but without success
Additional context
Pls provide some clear way how to use this plugin in a TypeScript project
Hi @Liwoj It will be appreciated if you can provide some detailed code to reproduce this. :)
IMO this is just a plugin used in vite, and it does not have any compatibility issues of TypeScript/JavaScript.
- Open
- Open new terminal
- run
npm run check
src/App.vue:2:25 - error TS2339: Property 'context' does not exist on type 'NodeRequire'.
2 const imports = require.context('./components');
- Open
- Open new terminal
- run
npm run check
src/App.vue:2:25 - error TS2339: Property 'context' does not exist on type 'NodeRequire'. 2 const imports = require.context('./components');
Any update on that?
Hi @Liwoj @iskendev Really sorry for the late replay.
It seems you forgot to add vite
and vue-tsc
in package.json
(Reproduction).
Anyway, I managed to reproduce this in my local project. I will try to figure out what's the problem today.
Thanks for your report.
Seems you need to add require.context
types(which is introduced by webpack
) to typescript like this:
npm install @types/webpack-env -D
Besides that, I also noticed the @types/webpack-env
declared the return value of function resolve
as string - this is different from webpack's require.context
. I have no idea why they declear it like this. So you also need to modify your code a little bit:
before:
const components = imports.keys().map((key) => imports.resolve(key).default);
after:
const components = imports.keys().map((key) => (imports.resolve(key) as any).default);
Hope this helps.