如何在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生成了<style>標簽,(當不提供ref引數時)注入到head中,成為了全域樣式,
于是,你的npm包的用戶不需要自己引入css檔案,也有樣式了!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/230315.html
標籤:其他
上一篇:深入了解頁面生命周期API
