Home > Categories > React > Typed CSS/SCSS Modules With ReactJS and NextJS
Home > Categories > Next js > Typed CSS/SCSS Modules With ReactJS and NextJS
Home > Typed CSS/SCSS Modules With ReactJS and NextJS
Typed CSS/SCSS Modules With ReactJS and NextJS
Updated:
Published:
Typescript has saved us from lots of spelling errors in javascript files.
But there is no built in support for CSS modules. Fortunately we can use plugins to fill that gap.
Same can be used for SCSS or SASS modules also. Without type safety I found myself making lots of spelling errors with css class names.
So we will add typed css modules in NextJS and ReactJS as follows.
To read rest of the article please Purchase Subscription
Before we get started with NextJS I would recommend to develop NextJS project inside development docker container.
So we no longer have the issue of "this works on my computer". And it will not mess with your existing workflow.
So checkout my blog post for detailed video explanation.
Then checkout react and NextJS development container settings on github.
Let's start with NextJS starter project with typescript enabled. Add dev dependency as follows.
npm i -D typescript-plugin-css-modules
Now we need to add the plugin in tsconfig.json
as follows
|
|
Then we need to add type definition file somewhere in the root. I have added in types->css.d.ts
|
|
The process for ReactJS is the same except skip the above step in react.
Now the MOST IMPORTANT STEP making it work with VS Code editor.
If you are not using VSCode then you can just skip to the end.
Create a new file at the root .vscode->settings.json
if it doesn't exist already. And add the following setting.
|
|
So in order for plugin to take effect VSCode must use typescript that is installed in `node_modules` folder of the project.
By default VSCode uses its own copy of typescript for improved performance.
Now open only single NextJS project in your workspace so these settings will take effect.
There will be pop up after these settings take effect. If there is no pop up then something has gone wrong. Make sure you click on Allow.
This is main trick of making typed css modules work with VSCode.
Now you can use autocomplete css modules in NextJS as follows
|
|
If you need to use SASS then just install it as dev dependency npm i -D sass
and rename files and use it as follows
|
|
In ReactJS it works the same way. Just renames classes to camel case as follows.
|
|
View complete source code on github
Conclusion
I know its lot of headache to setup typed css modules.
That you can only have single project in workspace for settings to take effect.
But the amounts of stupid spelling mistakes that you can avoid are priceless.
Free users cannot comment below so if you have questions then tweet me @apoorvmote. I would really like to hear your brutally honest feedback.
If you like this article please consider purchasing paid