typescript-plugin-css-modules
typescript-plugin-css-modules copied to clipboard
Using the global variable problem in Vite
Describe the bug Import the global variable in Vite, when the variable is used in another file, the prompt invalidates
To Reproduce Steps to reproduce the behavior:
- The scss file of a global variable is configured in vite
- Use global variables in other scss files 3.Yes, it's wrong
Expected behavior It should make no errors and parse the scss file correctly
Screenshots
global variable file(global variable are defined )
head.scss(using global variable)
After importing, using it throws an error
I put the variable in the head file and it worked fine
Desktop (please complete the following information):
- OS: Windows
- node Version: v20.11.1
Using "additionalData" to define your global variables may solve your problem.
Using "additionalData" to define your global variables may solve your problem.
I know, the above is my result after using additionalData, it is showing error, but it does not affect the compilation, I want to solve this problem
I'm experiencing the same issue. I can add arbitrary classes to additionalData, but adding any imports breaks it.
It also breaks the plugin for everything, not just files that make use of these globals, which makes me think it's not able to handle the relative imports unlike Vite.
As a temporary workaround, you can use allowUnknownClassnames, and drop use of additionalData. This will mean many of your files won't have strong typing if it depends on one of your globals.
I've found a fix for the problem, and a potential improvement in either the code or the docs (or both!).
This line sets up the alias imports: https://github.com/mrmckeb/typescript-plugin-css-modules/blob/4879b0418610eff871472ffa2cc592728d84d2be/src/helpers/getCssExports.ts#L117
It needs the presence of baseUrl and paths in your tsconfig to create an alias importer. baseUrl gets a default value, so this check does nothing, but paths need to exist (even if an empty object), to create the path matcher.
The easy fix is just to add the following to your tsconfig:
"compilerOptions": {
"paths": {}
}
This then allows the alias importer to resolve relative to your tsconfig, as well as relative to the file it is resolving.
Hi @RMHonor, that seems like a good change for us to make, as we shouldn't require an empty object. Would you be interested in opening a PR?
Edit: I've raised that as a bug here: https://github.com/mrmckeb/typescript-plugin-css-modules/issues/270
Also, if anyone can provide a repro for the initial issue, that would be greatly appreciated.
Fwiw, this workaround fixes an otherwise broken plugin; paths must be defined, even if it's just paths: {}