簡體   English   中英

是否可以從 Javascript 模塊導入 CSS 樣式?

[英]Is it possible to import CSS Styles from Javascript Modules?

我想導入 Google 字體並將自定義樣式添加到現有項目。 但是我只能訪問某些 JS 模塊。 無法訪問 HTML 或現有的 CSS 文件。

我添加樣式的唯一方法是使用如下所示的 JS 模塊:

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

module.exports = styles;

我嘗試在backticks之間或在styles.js文件的開頭添加 Google Fonts Import 或簡單的 CSS Import 語句,但沒有成功 - 兩者都不起作用。 (我在下面的一個代碼中包含了我所有的嘗試,但是當我測試時,我一次只使用了 1 行/導入語句。)

// 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 的fetch API 獲取外部腳本。 這是您想要實現的目標的可能代碼。

// 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;

請注意,我沒有在上面的代碼中進行任何錯誤處理。 由於處理錯誤是一種好習慣,所以我會要求您進行必要的錯誤處理。 :)

編輯:
使用 promises 上面的代碼:

// 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.
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM