React) Webpack Configuration for Compiling Sass with CSS Modules
// webpack.config.js의 일부
// sassRegex
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2, // css-loader가 처리하기 전에 2개의 로더(sass-loader와 postcss-loader)를 거칩니다.
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
}).concat({
loader: require.resolve("sass-loader"),
options: {
sassOptions: {
includePaths: [paths.appSrc + "/styles"],
},
additionalData: "@import 'utils';",
},
}),
sideEffects: true,
},
1. **Sass File Test**: The configuration object starts with a `test` property, which uses `sassRegex` to match files. This regular expression likely targets files with `.sass` or `.scss` extensions, determining which files should be processed by the loaders specified in the `use` array.
2. **Exclusion of Module Files**: The `exclude` property with `sassModuleRegex` likely specifies a pattern for files that are considered CSS Modules (typically files ending with `.module.sass` or `.module.scss`). This exclusion ensures a different configuration can be applied to those files, usually to enable CSS Modules' scoped styling.
3. **Use Array - Loaders Configuration**: The `use` property defines an array of loaders that tells Webpack how to process the matched Sass files.
- **getStyleLoaders**: A function call that returns an array of loaders configured for processing CSS. It likely includes `css-loader` and possibly `style-loader` or `MiniCssExtractPlugin.loader` depending on the environment (`development` or `production`). The `importLoaders: 2` option informs `css-loader` that there are two loaders that process the CSS before it does, which are `sass-loader` and `postcss-loader`.
- **Source Map Configuration**: Conditional source map generation is enabled based on the environment. In production, source maps are generated if `shouldUseSourceMap` is true; in development, they are always generated.
- The array is concatenated with an additional loader configuration for `sass-loader`.
4. **Sass Loader Configuration**: This part specifies the `sass-loader` and its options. `sass-loader` compiles Sass/SCSS files to CSS. The `sassOptions` object includes `includePaths`, which allows for easier import paths by adding the project's styles directory. The `additionalData` option automatically prepends the `@import 'utils';` statement to every Sass file processed, making shared variables, mixins, or functions from the `utils` file available across all Sass stylesheets without manually importing them in each file.
5. **Side Effects**: The `sideEffects: true` flag is set to inform Webpack that this loader's processing might have side effects, signaling that it should not tree-shake (remove what it considers unused exports) the CSS being imported. This is particularly important for stylesheets where the import side effects (applying styles) are the desired outcome.