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:`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.jsconst 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) => {
return (
)
}
export default demo
关于找一找教程网
本站文章仅代表作者观点,不代表本站立场,所有文章非营利性免费分享。
本站提供了软件编程、网站开发技术、服务器运维、人工智能等等IT技术文章,希望广大程序员努力学习,让我们用科技改变世界。
[在TSDX中引用css,less,样式文件并模块化样式]http://www.zyiz.net/tech/detail-150863.html