您可以通过以下方式使用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');
我想出了下面的动态文件加载代码
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');
}