Includes Gatsby V2 drop-in webpack support for SCSS stylesheets modules & automatic generation of accompanying typing declaration (.d.ts
) files.
yarn add --dev sass gatsby-plugin-scss-typescript
or
npm install --save-dev sass gatsby-plugin-scss-typescript
- Include the plugin in your
gatsby-config.js
file.
// gatsby-config.js
plugins: ['gatsby-plugin-scss-typescript'];
- Write your SCSS, import & use them as normal.
// component.ts
import * as styles from './styles.module.scss';
Only files that include the .module.scss
extensions shall be treated as module files, and hence have typings generated at build time. .scss
files shall be loaded using the regular css-loader with no additional magic.
The default gatsby rule loaders are used where possible, see the gatsby webpack utils for more info.
The declarationOptions
key is passed to typings-for-css-modules-loader.
The cssLoaderOptions
key is passed to the css-loader, with a few defaults from gatsby.
The sassLoaderOptions
key is passed to the sass-loader.
The cssMinifyOptions
key is passed to the OptimizeCssAssetsPlugin.
The cssExtractOptions
key is passed to the MiniCssExtractPlugin.
// in gatsby-config.js
plugins: [
{
resolve: 'gatsby-plugin-scss-typescript',
options: {
cssLoaderOptions: {
importLoaders: 1,
localIdentName: '[name]_[local]___[contenthash:base64:5]_[emoji:1]',
},
sassLoaderOptions: {
includePaths: [path.resolve(__dirname, './src/styles/scss')],
},
cssMinifyOptions: {
assetNameRegExp: /\.optimize\.css$/g,
canPrint: true,
},
cssExtractOptions: {
filename: '[name].css',
chunkFilename: '[id].css',
},
},
},
];
Firstly, thats not really a question, but we can take a stab at it.
Yes, it does generate a bunch of files, one for each .module.scss
file imported by a react component.
Thats better as a question. These are Typescript declaration files, they essentially describe a js module, such that TS can expect the details that are declared.
In this case they are describing what the scss will look like once it has been turned into a js module.
This is what is happening under the surface, when you write:
import styles from './styles.module.scss';
You are importing a js module that can be transpiled from your scss using a webpack loader.
No.
Well, maybe. You can have type safe css without these declaration files using typescript-plugin-css-modules in your tsconfig.json
.
For those who prefer to throw caution to the wind, you can use this:
declare module '*.scss' {
const content: { [className: string]: string };
export default content;
}
You animal. 🦁
Make sure your file are suffixed with .module.scss
, the plugin won't generate declarations for regular .scss
files by design. This is to give the most power to you!
No, and make sure you don't have other scss plugins like gatsby-plugin-sass
installed, they'll just disagree. gatsby-plugin-scss-typescript
achieves the same thing plus the type generation.
You will need sass
as a dependency of your project though!