1. require-context
Require with an expression.
require-context
Package: require-context
Created by: wilsonlewis
Last modified: Sun, 26 Jun 2022 11:36:20 GMT
Version: 1.1.0
License: MIT
Downloads: 59,217
Repository: https://github.com/wilsonlewis/require-context

Install

npm install require-context
yarn add require-context

require-context v1.1.0

Installation

Using npm:

 $ npm i -g npm
$ npm i --save require-context

In Node.js:

 // Load globally into all modules.
require('require-context/register')

// Load locally as a function.
var requireContext = require('require-context');

Usage

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.

The syntax is as follows:

 require.context(directory, useSubdirectories = false, regExp = /^\.\//)

Examples

 require.context("./test", false, /\.test\.js$/);
// a context with files from the test directory that can be required with a request endings with `.test.js`.
 require.context("../", true, /\.stories\.js$/);
// a context with all files in the parent folder and descending folders ending with `.stories.js`.

Context API

A context module exports a (require) function that takes one argument: the request.

The exported function has 3 properties: resolve, keys, id.

  • resolve is a function and returns the module id of the parsed request.
  • keys is a function that returns an array of all possible requests that the context module can handle.

This can be useful if you want to require all files in a directory or matching a pattern, Example:

 function importAll (r) {
  r.keys().forEach(r);
}

importAll(require.context('../components/', true, /\.js$/));

Why require-context?

  • Take the hassle out of requiring groups of modules
  • Write cross-platform code between webpack and node

Dependencies

RELATED POST

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin