front-end engineering automation with webpack require.context()

created at 09-20-2021 views: 3

1. Problem description

I don’t know if you keep importing when registering global components. I really want to write a loop to register public components. The require.context() function can satisfy this wish.

2. What is require.context()

It is a webpack API, when we want to import multiple files from a folder, we can use it, it will automatically traverse the specified files in the specified folder

3. How to use require.context()

The require.context() function receives three parameters

const files = require.context('@/components', true, /index\.vue$/)
  • '@/components': specify the folder path to traverse
  • true: whether to traverse the subdirectories of the file
  • /index\.vue$/: the regular expression that matches the file

4.require.context() return value

After the require.context() function is executed, it returns a function, which has three attributes

  • resolve
    Accept a parameter request, request is the relative path of the matching file under the test folder, and return the relative path of the matching file relative to the entire project
  • keys
    Returns an array of relative paths of successfully matched files
  • id
    The id of the execution environment, which returns a string

Example:

File Directory

File Directory

Traverse the index.vue file in the subdirectory of the components folder and mount the component to Vue

Traverse the index.vue file

Console output:

Console output

Introduced under the main.js folder

Introduced under the main.js folder

created at:09-20-2021
edited at: 09-20-2021: