如何在TSDX中引用css样式文件?
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
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;
},
};
再次打包,你观察一下dist/xxx.esm.js
文件,这是通过ESM方式时导入的文件(现在基本都是通过ESM导入了),多了一个函数styleInject
:
function styleInject(css, ref) {
if ( ref === void 0 ) ref = {
};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') {
return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
// ...
// 下面会有这些内容调用该函数
var css_28z = ".test-module_card__1YX84{background:#0ff;color:#7fffd4}";
styleInject(css_248z);
这个函数就是根据css生成了标签,(当不提供ref参数时)注入到head中,成为了全局样式。
于是,你的npm包的用户不需要自己引入css文件,也有样式了!