Dynamic imports in ES6 with runtime variables

后端 未结 1 383
感动是毒
感动是毒 2020-12-06 06:21

Recently stumbled upon the dynamic import proposal and also this Youtube video . Thought would be a great idea to use it for on demand imports of components in React.

<
相关标签:
1条回答
  • 2020-12-06 06:36

    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.

    0 讨论(0)
提交回复
热议问题