Use typescript for nothing more than its code constraints and hinting capabilities. Take react as an example:

The original structure

Component directory structure

Error
│   index.scss
│   index.tsx    
Copy the code

index.tsx

import * as React from 'react'

import * as styles from './index.scss'Const Error = () => (<div className={styles.centered}> <div className={styles.emoji}>😭</div> <p className={styles.title}>Ooooops! </p> <p>This page doesn't exist anymore.

) export default Error
Copy the code

index.scss

.centered {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
}

.emoji {
    font-size: 9em;
    user-select: none;
}

.title {
    font-size: 3em;
    text-align: center;
    color: gray;
}
Copy the code

In the case of no configuration, if no accident, error 😂

There are three main solutions

  1. Use require

    const styles = require('./index.scss')
    Copy the code

    Require is the default definition

  2. Adding a global declaration

    declare module '*.scss' {
      const content: any;
      export default content;
    }
    Copy the code

    Modify the import

    import styles from './index.scss'
    Copy the code
  3. Generate index.scs.d.ts for index.scss

As stated from the beginning, we use typescript for nothing more than its code constraints and hinting capabilities, so the third option is our best solution.

How to generate

typed-css-modules

github

The method of using typed csS-modules is relatively simple, mainly through the command line to generate D. ts, support watch mode

tcm src -c -w
Copy the code

It is also possible to develop plugins with the typed CSS-modules module

typings-for-css-modules-loader

github

Typings-for-css-modules-loader is a webpack loader. Modify the SCSS file rules at module in the WebPack configuration file

const typingsForCssModulesLoaderConf = {
    loader: 'typings-for-css-modules-loader',
    options: {
        modules: true,
        namedExport: true,
        camelCase: true,
        sass: true}}... [{test: /\.scss$/,
        exclude: resolve('src/commonStyles'),
        rules: [
            {
                use: ['style-loader', typingsForCssModulesLoaderConf]}}, {/ / don't use CSS in SRC/commonStyles moduletest: /\.scss$/,
        include: resolve('src/commonStyles'),
        rules: [
            {
                use: ['style-loader'.'css-loader'.'sass-loader']}]}Copy the code

To avoid webpack being slowed down by generating too many SCs.d. ts, add it in the WebPack plugin

new webpack.WatchIgnorePlugin([/css\.d\.ts$/])
Copy the code

Generate results

The final directory structure of the above two methods to generate D. ts is

Error │ index. SCSS │ index.scss.d.ts │ index. TSXCopy the code

index.scss.d.ts

export const centered: string;
export const emoji: string;
export const title: string;
Copy the code