zoukankan      html  css  js  c++  java
  • react按需加载(getComponent优美写法),并指定输出模块名称解决缓存(getComponent与chunkFilename)

    react配合webpack进行按需加载的方法很简单,Route的component改为getComponent,组件用require.ensure的方式获取,并在webpack中配置chunkFilename。
    const chooseProducts = (location, cb) => { require.ensure([], require => { cb(null, require('../Component/chooseProducts').default) },'chooseProducts') } const helpCenter = (location, cb) => { require.ensure([], require => { cb(null, require('../Component/helpCenter').default) },'helpCenter') } const saleRecord = (location, cb) => { require.ensure([], require => { cb(null, require('../Component/saleRecord').default) },'saleRecord') } const RouteConfig = ( <Router history={history}> <Route path="/" component={Roots}> <IndexRoute component={index} />//首页 <Route path="index" component={index} /> <Route path="helpCenter" getComponent={helpCenter} />//帮助中心 <Route path="saleRecord" getComponent={saleRecord} />//销售记录 <Redirect from='*' to='/' /> </Route> </Router> );


    旧写法

    <Route path="movieSearch/:keyWord"
      getComponent={
        (nextState, callback)=> {
          require.ensure([], (require)=> {
          callback(null, require("../containers/MovieSearchContainer.js").default)
        }, "movieSearch")
       }
      }
    />

     
    require-ensure 
      • 说明: require.ensure在需要的时候才下载依赖的模块,当参数指定的模块都下载下来了(下载下来的模块还没执行),便执行参数指定的回调函数。require.ensure会创建一个chunk,且可以指定该chunk的名称,如果这个chunk名已经存在了,则将本次依赖的模块合并到已经存在的chunk中,最后这个chunk在webpack构建的时候会单独生成一个文件。
      • 语法:require.ensure(dependencies: String[], callback: function([require]), [chunkName: String])
        • dependencies: 依赖的模块数组
        • callback: 回调函数,该函数调用时会传一个require参数
        • chunkName: 模块名,用于构建时生成文件时命名使用
      • 注意点:requi.ensure的模块只会被下载下来,不会被执行,只有在回调函数使用require(模块名)后,这个模块才会被执行。
     

    output: {
      path: path.resolve(__dirname, 'dist'),
      // filename应该比较好理解,就是对应于entry里面生成出来的文件名
      filename: 'bundle.js',
      // 为了做代码的异步加载,所有文件都以/代替根目录转换,即输入/就会自动转为根目录
      // “publicPath”项则被许多Webpack的插件用于在生产模式下更新内嵌到css、html文件里的url值,解决Link标签里的to用绝对路径问题
      publicPath:'/',
      // chunkname我的理解是未被列在entry中,却又需要被打包出来的文件命名配置。
      // 在按需加载(异步)模块的时候,CommonJS的方式异步加载模块:require.ensure() API,

      //异步加载的模块是要以文件形式加载哦,所以这时生成的文件名是以chunkname配置的,生成出的文件名,同时解决缓存问题
      chunkFilename: '[name]_[chunkhash:8]_chunk.js'
    }

  • 相关阅读:
    UVa 11300 Spreading the Wealth(有钱同使)
    hihoCoder 1385 : A Simple Job(简单工作)
    hihoCoder 1383 : The Book List(书目表)
    HDU 5724 Chess(国际象棋)
    Sobytiynyy Proyekt Casino Gym
    Course recommendation Gym
    Poor Folk Gym
    How far away? (HDU
    BAPC 2016 ----Brexit (BFS + vector)
    Simpsons’ Hidden Talents(扩展KMP)
  • 原文地址:https://www.cnblogs.com/zhjh256/p/7931516.html
Copyright © 2011-2022 走看看