A plugin that automatically creates a type file when using the CSS module type-safely.
npm i -D vite-plugin-sass-dtsFor version 1.3.27 or later, please use the latest sass-embedded package; we have confirmed that it does not work with the sass package.
import { defineConfig } from 'vite'
import sassDts from 'vite-plugin-sass-dts'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [sassDts()],
})You can create a dts file by saving the scss file during development. You can check the usage example when the following options are set. Prepare the vite.config.ts file with the following options and start it in development mode.
[vite.config.ts]
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import sassDts from 'vite-plugin-sass-dts'
import path from 'path'
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles" as common;`,
importer(...args) {
if (args[0] !== '@/styles') {
return
}
return {
file: `${path.resolve(__dirname, './src/assets/styles')}`,
}
},
},
},
},
plugins: [
react(),
sassDts({
enabledMode: ['development', 'production'],
global: {
generate: true,
outputFilePath: path.resolve(__dirname, './src/style.d.ts'),
},
sourceDir: path.resolve(__dirname, './src'),
outputDir: path.resolve(__dirname, './dist'),
}),
],
})npm run devThen save the following file ...
[src/assets/styles/_index.scss]
.row {
display: flex;
}[src/App.module.scss]
.header-1 {
background-color: common.$primary;
&.active {
background-color: black;
}
}
.input {
@media (min-width: 768px) {
max-width: 370px;
}
}Saving the scss file creates a d.ts file in the outputDir hierarchy.
Note: if
outputDiris not set, declaration files are output to the same directory as the source files.
TypeScript 5 Compatibility: By default, declaration files are generated in the format
*.d.scss.ts(e.g.,App.module.d.scss.ts) which is compatible with TypeScript 5's module resolution. To use the legacy format*.scss.d.ts, setlegacyFileFormat: truein the plugin options.
[dist/App.module.d.scss.ts]
import globalClassNames, { ClassNames as GlobalClassNames } from './style.d'
declare const classNames: typeof globalClassNames & {
readonly 'header-1': 'header-1'
readonly active: 'active'
readonly input: 'input'
}
export = classNamesThe optional global type definition is output to the output path of the common style specified in the options.
[src/style.d.ts]
declare const classNames: {
readonly row: 'row'
}
export = classNamesPlease see the principles of conduct when building a site.
This library is licensed under the MIT license.

