简体   繁体   English

Webpack; 如何动态导入 css

[英]Webpack; how to import css dynamically

After searching the web I cannot find a straight answer so my question is: Is it possible in webpack to import css files dynamically like so:搜索 web 后,我找不到直接答案,所以我的问题是:webpack 是否可以像这样动态导入 css 文件:

if(foo){
  import 'mobile.css'
} else {
  import 'desktop.css'
}

I tried this and it does not work;我试过了,但它不起作用; is there a workaround or special webpack module or else?是否有解决方法或特殊的 webpack 模块或其他?

This works for me:这对我有用:

const foo = false;
if (foo) {
  require("./mobile.css");
} else {
  require("./desktop.css");
}

Also you can use the dynamic import :您也可以使用动态导入

const foo = false;
if (foo) {
  import("./mobile.css");
} else {
  import("./desktop.css");
}

See: https://stackblitz.com/edit/js-hrvzy9?file=index.js请参阅: https://stackblitz.com/edit/js-hrvzy9?file=index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM