[Translation] webpack official website documentation: guide -- 13. Dependency management

Original translation, please indicate the source when reprinting.

Original address: https://webpack.js.org/guides/dependency-management/

 

  • es6 modules
  • commonjs
  • amd

 request by expression

When an expression is included in a module request, a context is created, so the exact module is not known at compile time.

example:

 

require("./template/"+ name +".ejs");

 

 

webpack analyzes require() and extracts some information:

 

Directory: ./template
Regular expression: /^.*\.ejs$/

 

 

context module

A context module is generated, containing references to all modules in this path, and can be used by requests matching the regular expression. The context module contains a map containing the correspondence between requests and module identities.

example:

 

{
    "./table.ejs":42,
    "./table-row.ejs":43,
    "./directory/folder.ejs":44
}

 

 

The context module also contains some runtime logic to access the map.

This means that dynamic requests are supported, but all related possible modules are packaged.

 

require.context

You can create your own context using the require.context() function. It allows you to pass in a path parameter to search for, an identifier for whether to allow subdirectories to be searched, and a regular expression to match against files.

webpack parses require.context() in the code at compile time.

The syntax is like this:

 

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

 

 

example:

 

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 Module API

A context module exports a (require) function with one parameter: request.

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

  • resolve: is a function that returns the module id corresponding to the request
  • keys: is a function that returns an array containing all the requests that the context module can handle.

This is helpful when you want to request all files in a directory or match an expression, for example:

 

function importAll (r){
  r.keys().forEach(r);
}
importAll(require.context('../components/',true,/\.js$/));

 

var cache = {};
function importAll (r){
  r.keys().forEach(key => cache[key]=r(key));
}
importAll(require.context('../components/',true,/\.js$/));
// At build-time cache will be populated with all required modules.
  •  id: is the id of the context module. Useful for module.hot.accept.

 

-- End --

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326778891&siteId=291194637