是否可以从Javascript模块导入CSS样式?



我想导入谷歌字体并添加自定义样式到现有项目。然而,我只能访问某些JS模块。无法访问HTML或现有的CSS文件。

我添加样式的唯一方法是使用一个JS模块,看起来像这样:

// styles.js
const styles = () => `
.custom-class {
font-size: 14px;
}
`;
module.exports = styles;

我已经尝试添加谷歌字体导入或一个简单的CSS导入声明两者之间的backticks或在styles.js文件的开始,没有成功-都不工作。(我把所有的尝试都包含在下面的代码中,但是当我在测试时,我一次只使用了一个line/import语句。)

// styles.js
import "./custom.css";
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
const styles = () => `
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
.custom-class {
font-size: 14px;
}
`;
module.exports = styles;

是否有可能以某种方式导入CSS文件到JS模块中,我可以在我的覆盖/新样式中使用导入的CSS行?

您可以使用JavaScript的fetchAPI获取外部脚本。下面是您想要实现的可能的代码。

// styles.js
async function getCSS(url) {
let response = await fetch(url);
return await response.text();
}
let myCSS = await getCSS('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
const styles = () => `
${myCSS}

.custom-class {
font-size: 14px;
}
`;
module.exports = styles;

请注意,在上面的代码中我没有做任何错误处理。由于处理错误是一种良好的实践,因此我要求您执行必要的错误处理。:)

编辑:
使用上面的代码:

// styles.js
function getCSS(url) {
return fetch(url).then(response => response.text());
}
const styles = new Promise((resolve, reject) => {
resolve(getCSS('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap'));
});
module.exports = styles;

从其他文件命名为

// otherFile.js
require('styles.js').then(result => {
// do whatever you want with the
// result. you can even add custom css here.
});

最新更新