资讯专栏INFORMATION COLUMN

webpack中require.context的使用

cyrils / 2514人阅读

摘要:我们按照提供的思路,对路由按业务模块进行拆分。这时就可以使用到了打包入口文件自动引入子目录下所有文件参考分享使用的实现路由去中心化管理之用法的基础组件的自动化全局注册官方文档

概述

You can create your own context with the require.context() function.

It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.

webpack parses for require.context() in the code while building.

webpack文档 - require.context

require.context是webpack中,用来创建自己的(模块)上下文;
webpack会在代码构建的时候去解析该函数
解析
require.context(directory, useSubdirectories = false, regExp = /^.//);

该方法有3个参数:

需要搜索的文件夹目录(必传)

是否需要搜索它的子孙目录,默认为false

匹配文件名的正则表达式

例子
// 示例
const test = require.context("./string", false, /.js$/);

我的目录结构如下:

String

trim.js

trimLeft.js

trimRight.js

test

test1.js

*

这时候如果console.log(test),就会发现调用require.context之后返回的是一个函数

webpackContext(req) {
  var id = webpackContextResolve(req);
  return __webpack_require__(id);
}

这次如果还需要深入就需要去webpack打包之后的文件中寻找了:

var map = {
    "./test/test1.js": "./src/string/test/test1.js",
    "./trim.js": "./src/string/trim.js",
    "./trimLeft.js": "./src/string/trimLeft.js",
    "./trimRight.js": "./src/string/trimRight.js"
};


function webpackContext(req) {
    var id = webpackContextResolve(req);
    return __webpack_require__(id);
}
function webpackContextResolve(req) {
    var id = map[req];
    if(!(id + 1)) { // check for number or string
        var e = new Error("Cannot find module "" + req + """);
        e.code = "MODULE_NOT_FOUND";
        throw e;
    }
    return id;
}
webpackContext.keys = function webpackContextKeys() {
    return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = "./src/string sync recursive .js$";

由上面的代码可以看出,在webpackContext定义了多个方法和属性

console.log(webpackContext.id) // "./src/string sync recursive .js$"

console.log(webpackContext("./trim.js")) // "./src/string/trim.js"

console.log(webpackContext.keys()) // ["./test/test1.js", "./trim.js", "./trimLeft.js", "./trimRight.js"]
使用场景 vue中的基础组件的自动化全局注册

具体就不多说了,直接看文档
vue官方文档 - 基础组件的自动化全局注册

大型单页应用中,路由过多

当你的单页应用变成了大型应用后,路由也在慢慢的增多

// rootRoute.js
const rootRoute = {
  childRoutes: [
    {
      path: "/",
      component: AppLayout,
      childRoutes: [
        {
          path: "shop", // 购买详情页
          component: ShopLayout,
          childRoutes: [
            {
              path: "foodDetail",
              component: FoodDetail
            },
            {
              path: "shoesDetail",
              component: ShoesDetail
            }
            // 其他
          ]
        },
        {
          path: "order", // 订单页
          component: Order,
          childRoutes: [
            {
              path: "remark", //订单备注
              component: Remark
            },
            {
              path: "invoice", //发票抬头
              component: Invoice
            },
            {
              path: "payment", //付款页面
              component: Payment
            },
            {
              path: "userValidation", //用户验证
              component: UserValidation
            },
            {
              path: "chooseAddress", //选择地址
              component: ChooseAddress,
              childRoutes: [
                {
                  path: "addAddress", //添加地址
                  component: AddAddress,
                  childRoutes: [
                    {
                      path: "searchAddress", //搜索地址
                      component: SearchAddress
                    }
                  ]
                }
              ]
            }
          ]
        }
        // ...
        // 大量新增路由
        // ...
      ]
    }
  ]
};

当路由变的越来越大,大到已经难以维护时。我们按照react-router提供的思路,对路由按业务模块进行拆分。

// rootRoute.js
const rootRoute = {
  childRoutes: [
    {
      path: "/",
      component: AppLayout,
      childRoutes: [
        require("./modules/shop/route"), //购买详情页
        require("./modules/order/route"), // 订单页
        require("./modules/login/route"), // 登录注册页
        require("./modules/service/route"), // 服务中心
        // ...
        // 其他大量新增路由
        // ...
      ]
    }
  ]
};

再进一步优化的话,就可以使用require.context

const rootRoute = {
  childRoutes: [
    {
      path: "/",
      component: AppLayout,
      childRoutes: (r => {
        return r.keys().map(key => r(key));
      })(require.context("./", true, /^./modules/((?!/)[sS])+/route.js$/))
    }
  ]
};
自动引用目录下的文件

比如我现在想要造一个自己的工具库utils,那么随着工具函数数量的增加,势必需要将代码分割得更小,甚至细化到一个工具函数对应一个js文件。

这时如果还需要在入口js文件中一个个手动引用,那么每增加一个js文件,就需要重新去修改入口js一次,工程量是非常大的。

这时就可以使用到require.context了~

/**
 * @desc webpack打包入口文件  
 * @example 自动引入子目录下所有js文件
 */
let moduleExports = {};

const r = require.context("./", true, /^./.+/.+.js$/);
r.keys().forEach(key => {
    let attr = key.substring(key.lastIndexOf("/") + 1, key.lastIndexOf("."));
    moduleExports[attr] = r(key);
});

module.exports = moduleExports;
参考

分享:使用 webpack 的 require.context 实现路由“去中心化”管理

webpack 之 require.context 用法

vue的基础组件的自动化全局注册

webpack官方文档 - require-context

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/99443.html

相关文章

  • 深入理解webpackrequire.context

    摘要:可以做做不到的事情。看完这段代码就不难理解文档中所说的会返回一个带有个的函数了。进阶深入探究源码我们知道在版本后,在加载模块时,可以指定模块加载模式,我们能使用几种方式来控制我们要加载的模块。 前言 require.context 其实是一个非常实用的 api。但是 3-4 年过去了,却依旧还有很多人不知道如何使用。 而这个 api 主要为我们做什么样的事情?它可以帮助我们动态加载我们...

    lncwwn 评论0 收藏0
  • 【翻译向】webpack2 指南(上)

    摘要:原文发布与抹桥的博客翻译向指南上前置定义代码包代码块安装代码分割代码分割是中最引人注目的功能之一。回调函数一个回调函数会被执行一次当所有依赖都被加载以后。对象的实现作为一个参数传递给这个回调函数。 原文发布与 抹桥的博客 -【翻译向】webpack2 指南(上) 前置定义 Bundle 代码包Chunk 代码块 安装 npm install webpack --save-dev 代码分...

    史占广 评论0 收藏0
  • webpack2.x 文文档 翻译 之 依赖管理 Dependency Management

    摘要:依赖管理该条已在中文网存在,点击这里表达式来调用当你的请求包含表达式,那个一个上下文环境将被创建。一个包含所有父文件夹和子及后代文件夹中以结尾的文件的上下文。一个函数,返回一个数组,包含上下文模块能够处理的所有的请求。 依赖管理 Dependency Management 该条已在webpack2.x中文网存在,点击这里 es6 modules commonjs amd 表达式...

    raledong 评论0 收藏0
  • Node.js 热更新(一)

    摘要:直到最近在使用微信机器人时,遇到了强烈的需求。增删文件后热更新上面的代码已经不小心实现了增加文件后热更新,因为表示检测的更新,如果增加一个,那么就变成,于是新模块不等于老模块不存在,从而使用注册事件监听器。 背景 刚思考这个话题的时候,首先想到的是 Vue 或 React 的组件热更新(基于 Webpack HMR),后来又想到了 Lua、Erlang 等语言的热更新,不过在实际开发 ...

    LancerComet 评论0 收藏0
  • webpack构建项目自动引用文件下所有指定类型文件

    摘要:需求背景是这样,下有个文件,在中导出所有的文件,需要做到在新增文件时,自动引入到中。 需求背景是这样,./api/modules/下有n个js文件,在./api/index中导出所有modules的js文件,需要做到在modules新增js文件时,自动引入到./api/index中。因为在网上找不到好的解决方案,只能自己动手了 那么我就需要一个可以需求所有文件列表的api,也就是req...

    mudiyouyou 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<