繁体   English   中英

Webpack - 模仿同步延迟导入

[英]Webpack - mimics synchronous lazy import

出于代码拆分的目的,我将我的“帖子”数据以文件 ie 分隔为 json 格式。 sample-post-1.json 然后我的<Post>组件旨在动态导入这些帖子(但导入必须同步才能预渲染工作),例如:

// router
<Post path="/post/:slug" />

// Post
class Post extends Component {
  constructor(props) {
    super(props)

    // try to dynamically lazy import, use import() to hint webpack we want to 
    // code split this module. but the "real" import needed to be sync
    import(`@/data/posts/${this.props.matches.slug}`)
    // require(...) doesnt work and throw error, no idea why. hence below
    const post = __webpack_require__(
      require.resolveWeak(`@/data/posts/${this.props.matches.slug}`)
    )

    this.state = { post }
  }

  render() {...}
}

以上工作,但感觉太hacky了,是否有其他方法可以在没有__webpack_require__ / require.resolveWeak情况下实现相同的结果?

您问题中的解决方案是我目前知道的唯一方法。

但是,代码中的require变量并非在所有情况下都存在(例如,带有 ES6 模块的库),因此这里有一个更通用的版本(仅使用__webpack_require__变量):

declare var __webpack_require__;
function WP_ImportSync(name_ending: string) {
    // Try to dynamically lazy import. Use import() to hint webpack we want to code split this module, but the "real" import needs to be synchronous.
    import(name_ending);
    
    //return __webpack_require__(require.resolve(name));
    const moduleID = Object.keys(__webpack_require__.m).find(a=>a.endsWith(name_ending));
    return __webpack_require__(moduleID);
}

就像你说的,它不漂亮,但它可以完成工作。 (当然,只要您知道父项目正在使用 webpack,因为标准化的import(...)函数没有我所知道的同步版本)

暂无
暂无

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

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