使用typescript無非就是因為它的程式碼約束和提示能力. 以react為例:
原始結構
元件目錄結構
Error
│ index.scss
│ index.tsx
複製程式碼
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.</p>
</div>
)
export default Error
複製程式碼
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;
}
複製程式碼
在不加任何配置的情況下, 如無意外, 報錯了?
拋開webpack, 在typescript來看, 不認識scss解決方法大體有三種
-
使用require寫法
const styles = require('./index.scss') 複製程式碼
require預設的定義
-
新增全域性宣告
declare module '*.scss' { const content: any; export default content; } 複製程式碼
修改import
import styles from './index.scss' 複製程式碼
-
為index.scss生成index.scss.d.ts
正如一開始所說, 使用typescript無非就是因為它的程式碼約束和提示能力, 那麼, 第三種才是我們的最優解.
怎麼生成
typed-css-modules
typed-css-modules的使用方法比較簡單, 主要通過命令列去生成d.ts, 支援watch模式
tcm src -c -w
複製程式碼
當然還可以通過引入typed-css-modules模組自行開發外掛
typings-for-css-modules-loader
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了