6

私のアプリケーションには、複数のテーマ スタイルがあります (それらは異なる個別の CSS スタイル ファイルと考えることができます)。importCSS モジュールの使用を開始したいのですが、最初のファイルの作成方法さえわかりません。

次の(単純な)ディレクトリ構造を想定してみましょう。

layouts/
    themeA/
        myComponent.css
    themeB/
        myComponent.css
    themeC/
        myComponent.css
components/
    myComponent.js

ユーザー設定に応じて、別の CSS を選択したいと考えています。これは、ブラウザー (またはサーバー上) で簡単に実行できます。しかし、どうすれば myComponent.css を myComponent.js に含めることができるでしょうか?

CSS モジュールによると、import使用しているファイルを使用する必要があります。だからimport styles from 'theme/myComponent.css。問題は、私が真のテーマを 1 つ持っているのではなく、3 つの異なる並行したテーマを持っていることです。

import styles from '' // <<<< from what?

return `<div class=${styles.caption></div>`

CSSモジュールを使用する場合、複数のレイアウト/テーマで作業することさえ可能ですか?

4

3 に答える 3

1

次の方法で、commonjs 構文を使用してモジュールを動的にインポートできます。

config.js:
   export default function(key){
    var themes = ['themea','themeb','themec'];
    return themes[key] || theme[0];
   }

main.js:
   import getConfig from './config.js';
   var styles = require('../css/' + getConfig(2) + '.css');

babel-loaderstyle-loader / css-loaderを必ず使用してください

動的ファイル読み込み用に以下のコードを思いつきました

var even = 0;
var themes = ['themea', 'themeb', 'themec'];
var currentConfig = 'themea';
require.context("../css", true, /.css$/)
var cache = Object.assign({}, require.cache);
require('../css/themea.css');
$('#small-button').click(function(){
  setConfig(themes[even]);
  even = (even+1) % 3;
});

function setConfig(config) {
  var modulename = '../css/' + currentConfig + '.css';
  Object.keys(require.cache).forEach(function(cacheKey) {
        Object.keys(cache).indexOf(cacheKey) < 0 ? delete require.cache[cacheKey] : null;
  });
  currentConfig = config;
  cache = Object.assign({}, require.cache);
  require('../css/' + currentConfig + '.css');
}
于 2016-07-10T20:21:09.837 に答える
-4

JavaScript で実行する場合は、if/else または switch ステートメントを実行できます。

var node = document.createElement("link").setAttribute("rel", "stylesheet") setAttribute("type", "text/css");

if (setting === 'A') {
    node.setAttribute("href", "layouts/themeA/myComponent.css");
} else if (setting === 'B') {
    node.setAttribute("href", "layouts/themeB/myComponent.css");
} else if (setting === 'C') {
    node.setAttribute("href", "layouts/themeC/myComponent.css");
}

document.getElementsByTagName('head').appendChild(node);

またはjQueryで:

var href;

if (setting === 'A') {
    href = "layouts/themeA/myComponent.css";
} else if (setting === 'B') {
    href = "layouts/themeB/myComponent.css";
} else if (setting === 'C') {
    href = "layouts/themeC/myComponent.css";
}

$('head').append('<link href="' + href +'" rel="stylesheet" type="text/css" />');
于 2016-07-08T17:19:11.683 に答える