简体   繁体   English

webpack2动态样式文件要求

[英]webpack2 dynamic style file require

I am working with webpack 2 and I want to include some style file that depends from different NODE_ENV. 我正在使用webpack 2,我想包含一些样式文件,这些样式文件取决于不同的NODE_ENV。

I did something like this: 我做了这样的事情:

const stylesEntryName = process.env.SECOND_CLIENT ? "main_for_second_client" : "main";
const entryUrl = `assets/styles/${stylesEntryName}.styl`;


console.log("stylesEntryName ====>>> ", stylesEntryName, entryUrl);


require(entryUrl);

But it isn't working somehow. 但这不起作用。 I have got an error: Critical dependency: the request of a dependency is an expression 我有一个错误: 关键依赖项:依赖项的请求是一个表达式

the console shows: stylesEntryName ====>>> main assets/styles/main.styl 控制台显示: stylesEntryName ==== >>>主要资产/styles/main.styl

Maybe I do something wrong? 也许我做错了什么? (in case of direct url) (如果是直接网址)

require('assets/styles/main.styl');

the code working fine. 代码工作正常。

Thanks for any help. 谢谢你的帮助。

webpack is emitting that warning about the line require(entryUrl) because the value of the entryUrl variable is unknown until the code is executed (ie, the require is not statically analyzable). webpack发出关于行require(entryUrl)警告,因为在执行代码之前,entryUrl变量的值是未知的(即,require不能被静态分析)。 Here's the webpack documentation about that: https://webpack.github.io/docs/context.html#critical-dependencies 这是关于此的webpack文档: https ://webpack.github.io/docs/context.html#critical-dependencies

You can fix this problem by removing the dynamic require, and instead use if-else statements to pick a static require statement out of the possible choices. 您可以通过删除动态require来解决此问题,而可以使用if-else语句从可能的选择中选择一个静态require语句。 Here's code that does that for your issue: 这是针对您的问题的代码:

if (process.env.SECOND_CLIENT === 'main_for_second_client') {
  require('assets/styles/main_for_second_client.styl')
} else {
  require('assets/styles/main.styl')
}

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

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