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