依赖管理
webpackjsorg-main指南-教程
依赖管理
import() 或 require() 中的动态表达式
如果你的请求包含表达式,就会创建一个上下文(context),因此在编译时无法知道确切的模块。
例如,假设我们有以下包含 .ejs 文件的文件夹结构:
text
example_directory
└── template/
├── table.ejs
├── table-row.ejs
└── directory/
└── another.ejs
当以下 import() 或 require() 调用被执行时:
js
import(`./template/${name}.ejs`);
require(`./template/${name}.ejs`);
Webpack 会解析 import() 或 require() 调用并提取一些信息:
text
Directory: ./template
Regular expression: /^.*\.ejs$/
上下文模块(context module)
Webpack 会生成一个上下文模块。它包含对该目录中所有模块的引用,这些模块可以通过匹配该正则表达式的请求进行 require。上下文模块包含一个将请求转换为模块 id 的映射表。
示例映射:
json
{
"./table.ejs": 42,
"./table-row.ejs": 43,
"./directory/another.ejs": 44
}
上下文模块还包含一些用于访问该映射表的运行时逻辑。
这意味着动态调用是受支持的,但会导致所有匹配的模块都被包含在 bundle 中。
import.meta.webpackContext
require.context 的 ESM 等价写法是 import.meta.webpackContext。
js
import.meta.webpackContext(directory, {
recursive: true,
regExp: /^\.\/.*$/,
mode: "sync",
});
警告: 传递给
import.meta.webpackContext的参数必须是字面量!
require.context
你可以使用 require.context() 函数创建自己的上下文。
它允许你传入一个要搜索的目录、一个指示是否也应搜索子目录的标志,以及一个用于匹配文件的正则表达式。
在构建时,Webpack 会在代码中解析 require.context()。
语法如下:
js
require.context(
directory,
(useSubdirectories = true),
(regExp = /^\.\/.*$/),
(mode = "sync"),
);
示例:
js
require.context("./test", false, /\.test\.js$/);
// a context with files from the test directory that can be required with a request ending with `.test.js`.
js
require.context("../", true, /\.stories\.js$/);
// a context with all files in the parent folder and descending folders ending with `.stories.js`.
警告: 传递给
require.context的参数必须是字面量!
上下文模块 API
上下文模块导出一个(require)函数,该函数接受一个参数:请求(request)。
导出的函数有 3 个属性:resolve、keys 和 id。
resolve是一个函数,返回解析后的请求的模块 id。keys是一个函数,返回一个数组,包含该上下文模块可以处理的所有可能的请求。
如果你想 require 某个目录中的所有文件或匹配某个模式的文件,这会很有用。示例:
js
function importAll(r) {
r.keys().forEach(r);
}
importAll(
import.meta.webpackContext("../components/", {
recursive: true,
regExp: /\.js$/,
}),
);
js
const cache = {};
function importAll(r) {
for (const key of r.keys()) cache[key] = r(key);
}
importAll(
import.meta.webpackContext("../components/", {
recursive: true,
regExp: /\.js$/,
}),
);
// At build-time cache will be populated with all required modules.
id是上下文模块的模块 id。这对于import.meta.webpackHot.accept或module.hot.accept可能很有用。
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
