js当中对代码拆分时require.ensure()和import()的使用介绍及对比

2021-02-12 15:21

阅读:657

 import()

    这个的进口不同于模块引入时的导入,可以理解为一个动态加载的模块的函数(函数等),传入其中的参数就是相应的模块。例如对于原有的模块引入从 ‘反应‘ 导入写为进口(‘反应‘)但是需要注意的是,进口()会返回一个无极对象因此,可以通过如下方式使用:

    btn.addEventListener(‘click‘,e => {

        //在这里加载聊天组件相关资源chat.js

        import(‘/ components / chart‘)。then(mod => {

            someOperate(MOD);

        });

    });

    可以看到,使用方式非常简单,和平时我们使用的承诺并没有区别当然,也可以再加入一些异常处理:  

  btn.addEventListener(‘click‘,e => {

        import(‘/ components / chart‘)。then(mod => {

            someOperate(MOD);

        })。catch(err => {

            的的console.log(‘失败‘);

        });

    });

当然,由于进口()会返回一个承诺对象,因此要注意一些兼容性问题。解决这个问题也不困难,可以使用一些承诺的填充工具来实现兼容。可以看到,动态导入()的方式不论在语意上还是语法使用上都是比较清晰简洁的。

VUE使用实例

例:require.ensure()实现
const notFound = r => require.ensure([], () => r(require(‘@views/common/404‘)), ‘index‘)
const login = r => require.ensure([], () => r(require(‘@views/common/login‘)), ‘index‘)
const register = r => require.ensure([], () => r(require(‘@views/common/register‘)), ‘index‘)
const main = r => require.ensure([], () => r(require(‘@views/main‘)), ‘index‘)
const myWorks = r => require.ensure([], () => r(require(‘@views/my/index‘)), ‘my‘)
const myAccountSetting = r => require.ensure([], () => r(require(‘@views/my/account-setting‘)), ‘my‘)
const makeIndex = r => require.ensure([], () => r(require(‘@views/make/index‘)), ‘make‘)
例:import()实现
const notFound = () => import(/* webpackChunkName: "index" */ ‘@views/common/404‘)
const login = () => import(/* webpackChunkName: "index" */ ‘@views/common/login‘)
const register = () => import(/* webpackChunkName: "index" */ ‘@views/common/register‘)
const main = () => import(/* webpackChunkName: "index" */ ‘@views/main‘)
const myWorks = () => import(/* webpackChunkName: "my" */ ‘@views/my/index‘)
const myAccountSetting = () => import(/* webpackChunkName: "my" */ ‘@views/my/account-setting‘)
const makeIndex = () => import(/* webpackChunkName: "make" */ ‘@views/make/index‘)

 

上一篇:JS-CSS3

下一篇:php常用框架


评论


亲,登录后才可以留言!