[译]webpack官网文档 :指南 -- 13.依赖管理

原创翻译,转载请注明出处。

原文地址:https://webpack.js.org/guides/dependency-management/

 

  • es6 modules
  • commonjs
  • amd

 通过表达式请求

模块请求里包含表达式的时候,就会创建一个上下文环境,所以在编译的时候还不知道确切的模块。

例子:

 

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

webpack分析require(),并提取一些信息:

 

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

上下文模块

会生成一个上下文模块,包含了这个路径里所有模块的引用,跟正则表达式匹配的请求可以使用它。上下文模块包含一个映射,包含请求和模块标识之间的对应关系。

例子:

 

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

上下文模块还包含一些访问映射的运行时逻辑。

这就意味着支持动态的请求,但是所有有关联可能的模块都被打到包里了。

 

require.context

你可以使用require.context()函数创建自己的上下文。它允许你传入一个用于查找的路径参数,一个是否允许查找子目录的标识,和一个用来匹配文件的正则表达式。

webpack在编译的时候在代码里解析require.context()。

语法像这样:

 

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

例子:

 

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`.

 

上下文模块API

一个上下文模块导出一个 (require)函数,带有一个参数:request。

导出的函数带有三个属性:resolve, keys, id。

  • resolve:是一个函数,返回请求对应的模块id
  • keys:是一个函数,返回一个数组,包含了上下文模块能处理的所有请求。

这在你想请求一个目录里所有文件或匹配一个表达式时会有帮助,例子:

 

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:是上下文模块的id。对module.hot.accept有用。

-- End --

猜你喜欢

转载自stef.iteye.com/blog/2366290
今日推荐