神秘的行,用于在 Webpack 中需要 html 模板:templates.keys().forEach(templa

Mysterious line, used to require html templates in Webpack: templates.keys().forEach(templates)?

本文关键字:模板 html templates keys forEach templa 用于 Webpack      更新时间:2023-09-26

我想使用 ngTemplate-loader 和 html-template-loader 将 html 模板导入到 Webpack bundle 中,并在另一个项目中找到了用于该目的的两行代码:

const templates = require.context(__dirname, true, /'.html$/);
templates.keys().forEach(templates);

第一行对我来说很清楚 - 它递归地需要当前目录下的所有 html 文件,将它们添加到$templateCache。

但第二行对我来说完全是迷雾。它的意义何在?

templates.keys()将返回匹配文件的路径数组:

['./file1.js', './file2.js'].forEach(templates);

然后forEach将为每个文件调用templates函数(在上下文设置为 __dirname 的情况下require):

templates('./file1.js');
templates('./file2.js');

或:

require('./file1.js'); // this files will be searched relative to __dirname
require('./file2.js');