Context
I'm building a Vue app (using the Composition API) in TypeSript and I'm running into an issue that I'm sure has been explained many times, but I just can't find a solution or even know how to best formulate the question. (In case that matters, I'm using Vite and VS Code.)
I have a TS file that contains types, interfaces, enums, classes and functions that are meant to be used globally.
Currently, in every single other .vue or .ts file, I have a lengthy import statement that imports everything I need from that file. As you can imagine, this is quite unwieldy.
Is there a way to make all the contents of that helper file usable everywhere, without having to import it?
Things I've tried
- Using Vue's global properties
This isn't recommended or documented for projects using the Composition API and
script setup, which is what I'm doing. Besides, it doesn't work for enums, types or classes, as far as I could tell.
- Using Vue's provide/inject or composables features
This is equivalent to using
imports, it just adds an extra step. Unless I'm missing something.
- Importing the file in
main.ts, then augmenting the global scope usingdeclare global {}so that TS doesn't complain
I don't know if this is a good practice (probably not) or if it even is supposed to work. I didn't manage to get it to behave. In particular, I didn't know how to get this to behave with classes, I kept getting
Declaration or statement expectedorNo implementation allowed in ambient contextserrors.
- Using option 3 for types only, and importing everything else
That's what I ended up doing and it makes it sliiiightly more manageable as types is what I need a majority of the time, but I really wish I could find a way to do this for enums as well at the very least.
To sum up...
Is there a best practice for making all kinds of things from a single file available to an entire project without having to rely on import statements?
Edit to clarify:
I know polluting the global object is bad. I'm not asking how to do that! I'm looking for solutions to not do that, while also not having to add 20 lines of imports to each file.
I know it's doable:
- Rollup's inject plugin automatically adds import statements everywhere needed based on a configuration file you create once
- unplugin-auto-import, as the name suggests, auto-imports APIs based on a list of presets
These two tools enable you to use the stuff you need everywhere without having to worry about making it available. (I actually use the latter, but didn't manage to get the former to work with Vite.) How can I do the same thing with helpers and utilities that exist in a file locally?