16

最近偶然发现了动态导入提案和这个Youtube 视频。认为将它用于 React 中组件的按需导入是一个好主意。

import遇到一个问题,当将字符串文字作为运行时变量传递时,我无法“解析”路径。

例如:

<div>
  <button onClick={this._fetchComp.bind(this, "../component/Counter")}>Get Async Comp</button>
</div>

尝试了 _fetchComp 的多个选项,但传递参数似乎不起作用。尝试的不同选项的细分。

  1. 模板字符串 不起作用:单击时出现以下错误

错误:找不到模块“../components/Counter”。在 webpackAsyncContext (^.*$:53)

代码

    _fetchComp(res) {
    import(`${res}`).then(() => {
        console.log("Loaded")
    },(err)=>{
        console.log("Error",err)
    })}
  1. 变量不起作用:在webpack构建期间出现错误 55:12-23

关键依赖:依赖的请求是一个表达式

**Code**

    _fetchComp(res) {
    import(res).then(() => {
        console.log("Loaded")
    },(err)=>{
        console.log("Error",err)
    })}
  1. 字符串文字 作品: 只是传递纯字符串文字。单击时,我可以在开发工具网络选项卡中看到正在下载的块

    代码

    _fetchComp(res) {
    import("../components/Counter").then(() => {
        console.log("Loaded")
    },(err)=>{
        console.log("Error",err)
    })}
    

根据规范,

import() 接受任意字符串(此处显示的是运行时确定的模板字符串),而不仅仅是静态字符串文字。

所以我希望字符串文字能起到作用,但情况似乎并非如此。

我在flow issue tracker上遇到了类似的问题。但提议的解决方案再次提倡使用字符串文字。

我会给大家留下一个CodeSandbox 链接。

4

1 回答 1

34

The rules for import() for the spec are not the same rules for Webpack itself to be able to process import(). For Webpack to handle an import, it needs to be able to at least guess roughly what an import() is meant to be referencing.

This is why your example of import("../components/Counter") works, because Webpack can be 100% confident in what needs to be loaded.

For your usecase, you could for instance do

_fetchComp(res) {
  import(`../components/${res}`).then(() => {
    console.log("Loaded")
  }, (err)=>{
    console.log("Error", err)
  })
}

with

this._fetchComp.bind(this, "Counter")

and now that Webpack knows that the path starts with ../components/, it can bundle up every component automatically and then load the one you need. The downside here is that because it doesn't know which component you're loading, it has to load them all and there's no guarantee they are all actually being used. That is the tradeoff of dynamic imports.

于 2017-12-23T21:12:19.177 回答