I want to import Google Fonts and add custom stlyes to an existing project. However I only have access to certain JS modules. No access to HTML or existing CSS files.
The only way for me to add styles is using a JS module which looks like this:
// styles.js
const styles = () => `
.custom-class {
font-size: 14px;
}
`;
module.exports = styles;
I have tried adding Google Fonts Import or a simple CSS Import statement both between the backticks
or in the beginning of the styles.js
file, without success - neither works. (I've included all my tries in one code below, but when I was testing, I only used 1 line/import statement at a time.)
// 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;
Is it possible somehow to import CSS files into a JS Module in a way, that I can use the imported CSS lines in my overrides/new stlyes?
You can fetch the external script using JavaScript's fetch
API. Here's the possible code for what you want to achieve.
// 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;
Please note that I haven't done any error handling in the above code. Since it is a good practice to handle errors, so I would request you to do the necessary error handling. :)
Edits:
Using promises the above code:
// 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;
From other file call it like this
// otherFile.js
require('styles.js').then(result => {
// do whatever you want with the
// result. you can even add custom css here.
});