TSDX默认是不反对引入css款式的,遇到 import xxx.css 会提醒:
✖ Failed to compileError: Unexpected token (Note that you need plugins to import files that are not JavaScript)

解决办法

在我的项目根目录,新建tsdx.config.js

`const postcss = require('rollup-plugin-postcss');module.exports = {  rollup(config, options) {    config.plugins.push(      postcss({        inject: false,        extract: !!options.writeMeta,      }),    );    return config;  },};` 

并装置这个插件:

npm i -D rollup-plugin-postcss postcss

tsdx.config.js作用是批改TSDX的rollup配置(TSDX是基于rollup封装的,通过这个文件裸露接口,咱们能够间接批改rollup配置)。利用rollup-plugin-postcss这个rollup配套的插件,咱们就能够引入css啦!

成果

之后在我的项目中 import 'xxx.css',TSDX发现这句话,就会将之打包,你会在dist文件夹中看到xxx.cjs.development.css这个文件,就是输入的css文件啦。

留神:这只会打包出css文件,具体让你的npm包的用户 怎么援用呢?

咱们开发的是npm包,款式何时援用,最好让用户来决定!所以用户在应用时,也须要独自一句话援用咱们的css文件:

import 'xxx/xxx.cjs.development.css'

当然,如果你感觉你的npm包,用户肯定须要引入css,你也能够通过被动“注入css”的形式,益处是用户不须要手动引入css文件,怎么做?批改tsdx.config.js中的一个配置即可 inject: true

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.js

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(这个文件名能够自定义啦) 代码如下

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