【发布时间】:2019-03-20 02:14:46
【问题描述】:
设置:react、webpack、常规 css 和样式加载器,没什么花哨的
我希望能够在构建步骤中替换导入的文件。就像我使用 env WITH_THEME=true 构建应用程序时,将一个 css 文件替换为另一个名称不同的 css 文件。
例如,我有 2 个 css 文件,style.css 和 style.theme.css,在 react 组件中我只导入了一个类似 import './style.css' 的文件(我不想更改这一行,我知道可以在此处使用 env var 设置 if 条件)。
所以,如果我以 WITH_THEME=true 启动 webpack,我希望它实际导入 style.theme.css 而不是常规的 style.css,但前提是 style.theme.css 存在。
我想出了这个解决方案,它是加载器的测试条件:
// ...
test: filePath => {
if (!/\.(s*)css$/.test(path.extname(filePath))) {
return false;
}
const { dir, name, ext } = path.parse(filePath);
const themeFilePath = `${dir}/${name}.theme${ext}`;
if (WITH_THEME && fs.existsSync(themeFilePath)) {
return false;
} else {
return true;
}
},
// ...
但是通过这种方式,我需要在组件中同时导入style.css 和style.theme.css,这样webpack 就可以排除其中一个。有一个更好的方法吗?也许有一些 post-css 解决方案?
【问题讨论】: