简体   繁体   English

Webpack / ES6动态导入

[英]Webpack / ES6 dynamic import

I'm using ES6 dynamic import to load a Sass file, according to an environment variable. 根据环境变量,我正在使用ES6动态导入来加载Sass文件。

It's working fine, but when I build the production directory with Webpack, all the Sass files are exported as a JS chunk in the build directory. 它工作正常,但是当我使用Webpack构建生产目录时,所有Sass文件都作为JS块导出到构建目录中。

After some research, I finally understand that import() look for similar files with the same path (only when I put a variable in the import) 经过一些研究,我终于明白import()会查找具有相同路径的类似文件(仅当我在导入中放入变量时)

It's quite problematic, I'd like to get the correct Sass file exported, and not the others. 这很成问题,我想要导出正确的Sass文件,而不是其他文件。

import(`./assets/scss/App.${brandName}.scss`)

Any idea ? 任何想法 ?

Normally, you can't do that! 通常情况下,你不能这样做!

Because import statement must be at the top. 因为import语句必须位于顶部。 Thus, you cannot define the variable before import statement. 因此,您无法在import语句之前定义变量。 Hence, you cannot utilize the variable in import statements. 因此,您无法在import语句中使用该变量。


But, you can trick to use like this: 但是,你可以这样使用:

import brandName from 'your_path_to_brandName_export'
import(`./assets/scss/App.${brandName}.scss`)

Update 更新

I am not sure about dynamic import, but it might help you further. 我不确定动态导入,但它可能会对您有所帮助。 See this proposal : 看到这个提议

<script type="module">
  import * as module from './utils.mjs';
  module.default();
  // → logs 'Hi from the default export!'
  module.doStuff();
  // → logs 'Doing stuff…'
</script>

See this source for further help. 请参阅此来源以获取进一步帮助

Hope, this helps! 希望这可以帮助!

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

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