CSS in Typescript

使用typescript無非就是由於它的代碼約束和提示能力. 以react爲例:css

原始結構

組件目錄結構react

Error
│   index.scss
│   index.tsx    
複製代碼

index.tsxwebpack

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.</p> </div> ) export default Error 複製代碼

index.scssgit

.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;
}
複製代碼

在不加任何配置的狀況下, 如無心外, 報錯了😂 github

拋開webpack, 在typescript來看, 不認識scss

解決方法大致有三種

  1. 使用require寫法web

    const styles = require('./index.scss')
    複製代碼

    require默認的定義 typescript

  2. 添加全局聲明sass

    declare module '*.scss' {
      const content: any;
      export default content;
    }
    複製代碼

    修改importbash

    import styles from './index.scss'
    複製代碼
  3. 爲index.scss生成index.scss.d.tsoop

正如一開始所說, 使用typescript無非就是由於它的代碼約束和提示能力, 那麼, 第三種纔是咱們的最優解.

怎麼生成

typed-css-modules

github

typed-css-modules的使用方法比較簡單, 主要經過命令行去生成d.ts, 支持watch模式

tcm src -c -w
複製代碼

固然還能夠經過引入typed-css-modules模塊自行開發插件

typings-for-css-modules-loader

github

typings-for-css-modules-loader是一個webpack loader. 在webpack配置文件中的module處修改scss文件規則

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]
            }
        ]
    },
    {
        // 位於src/commonStyles裏的不使用css module
        test: /\.scss$/,
        include: resolve('src/commonStyles'),
        rules: [
            {
                use: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    }
]
複製代碼

爲了不webpack由於生成衆多的scss.d.ts而致使速度變慢,在webpack plugin處添加

new webpack.WatchIgnorePlugin([/css\.d\.ts$/])
複製代碼

生成結果

以上兩種生成d.ts的方法最終的目錄結構都爲

Error
│   index.scss
│   index.scss.d.ts
│   index.tsx    
複製代碼

index.scss.d.ts

export const centered: string;
export const emoji: string;
export const title: string;
複製代碼

終於能夠愉快地使用scss中的className了
相關文章
相關標籤/搜索