TSDX默認是不支持引入css樣式的,遇到
import xxx.css
會提示:
✖ Failed to compile Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
在項目根目錄,新建tsdx.config.js
:css
`const postcss = require('rollup-plugin-postcss'); module.exports = { rollup(config, options) { config.plugins.push( postcss({ inject: false, extract: !!options.writeMeta, }), ); return config; }, };`
並安裝這個插件:react
npm i -D rollup-plugin-postcss postcss
tsdx.config.js
做用是修改TSDX的rollup配置(TSDX是基於rollup封裝的,經過這個文件暴露接口,咱們能夠直接修改rollup配置)。利用rollup-plugin-postcss
這個rollup配套的插件,咱們就能夠引入css啦!shell
以後在項目中 import 'xxx.css'
,TSDX發現這句話,就會將之打包,你會在dist文件夾中看到xxx.cjs.development.css
這個文件,就是輸出的css文件啦。npm
注意:這隻會打包出css文件,具體讓你的npm包的用戶 怎麼引用呢?sass
咱們開發的是npm包,樣式什麼時候引用,最好讓用戶來決定!因此用戶在使用時,也須要單獨一句話引用咱們的css文件:bash
import 'xxx/xxx.cjs.development.css'
固然,若是你以爲你的npm包,用戶必定須要引入css,你也能夠經過主動「注入css」的方式,好處是用戶不須要手動引入css文件,怎麼作?修改tsdx.config.js
中的一個配置便可 inject: true
:less
const postcss = require('rollup-plugin-postcss'); module.exports = { rollup(config, options) { config.plugins.push( postcss({ inject: true, // 這裏改成了 true extract: !!options.writeMeta, }), ); return config; },
接下來就要修改tsdx.config.js 使他能支持less和模塊化
安裝模塊化
npm install less postcss-modules --save-dev
而後配置tsdx.config.jspost
const postcss = require('rollup-plugin-postcss'); module.exports = { rollup(config, options) { config.plugins.push( postcss({ inject: true, extract: !!options.writeMeta, modules: true, // 使用css modules // namedExport: true, // 類名導出 camelCase: true, // 支持駝峯 // sass: true, // 是否使用sass // less:true, // autoModules:true, // namedExports(name) { // // Maybe you simply want to convert dash to underscore // return name.replace(/-/g, '_') // } }), ); return config; }, };
最後由於是typeScript代碼 須要在src文件夾下建立一個index.config.ts(這個文件名能夠自定義啦) 代碼以下ui
declare module '*.less' { const content: any; export default content; }
這樣的就能夠支持模塊化了~~~~
import React from 'react' import style from "./../index.less" interface Props { } const demo:React.FC<Props> = (props:Props) => { return ( <div className={style.title}> </div> ) } export default demo