新年好呀~过个年光打游戏,function都写不顺溜了。

  上一节的代码到这里了:

// NormalModuleFactory的resolver事件流
this.plugin("resolver", () => (data, callback) => {
// ... asyncLib.parallel( /*...*/ ,
/*
results:
[
[],
{
resourceResolveData:
{
context: { issuer: '', compiler: undefined },
path: 'd:\\workspace\\doc\\input.js',
request: undefined,
query: '',
module: false,
file: false,
descriptionFilePath: 'd:\\workspace\\doc\\package.json',
descriptionFileData: [Object],
descriptionFileRoot: 'd:\\workspace\\doc',
relativePath: './input.js',
__innerRequest_request: undefined,
__innerRequest_relativePath: './input.js',
__innerRequest: './input.js'
},
resource: 'd:\\workspace\\doc\\input.js'
}
]
*/
(err, results) => {
// ...超多内容
});
});

  经过长长的resolve,最终也只是解析入口文件的合法路径信息,然后调用回调函数。

  接下来分析回调函数是如何处理返回结果的:

// NormalModuleFactory的resolver事件流
this.plugin("resolver", () => (data, callback) => {
// ... asyncLib.parallel( /*...*/ ,
(err, results) => {
if (err) return callback(err);
// 暂时不存在loaders
let loaders = results[0];
const resourceResolveData = results[1].resourceResolveData;
resource = results[1].resource; // 跳过下面几部分内容
// translate option idents
try {
loaders.forEach(item => {
if (typeof item.options === "string" && /^\?/.test(item.options)) {
item.options = this.ruleSet.findOptionsByIdent(item.options.substr(1));
}
});
} catch (e) {
return callback(e);
} if (resource === false) {
// ignored
return callback(null,
new RawModule(
"/* (ignored) */",
`ignored ${context} ${request}`,
`${request} (ignored)`
)
);
} const userRequest = loaders.map(loaderToIdent).concat([resource]).join("!"); // 尝试获取路径参数
let resourcePath = resource;
let resourceQuery = "";
const queryIndex = resourcePath.indexOf("?");
if (queryIndex >= 0) {
resourceQuery = resourcePath.substr(queryIndex);
resourcePath = resourcePath.substr(0, queryIndex);
} // 很久之前的东西
const result = this.ruleSet.exec({
resource: resourcePath,
resourceQuery,
issuer: contextInfo.issuer,
compiler: contextInfo.compiler
}); // ...
});
});

  返回的结果有两部分,一个是loader,一个是文件对应路径。

  对于入口文件的当前解析,不存在loader,所以会直接跳过开始的几部分内容,直接进入后面的ruleSet方法处理。

ruleSet.exec

  这个ruleSet是个很久远的东西了,在18-19节有讲,主要是对配置文件中的modules.rules进行二次处理,包装在一个对象中。

  这里的exec方法主要是判断路径信息是否符合配置文件中定义的rules并解析返回一个result,方法如下(原型方法改成箭头函数好看一点):

exec = (data) => {
const result = [];
this._run(data, {
rules: this.rules
}, result);
return result;
}

  真正的判断方法是_run,其中data为传进来的判断对象,rules为判断标准,result是返回的结果。

  简答过一下内容:

/*
module.rules =>
[
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.css$/,
loader: 'css!style-loader'
},
{
test: /\.js$/,
loader: 'babel-loader'
},
]
data =>
{
resource: 'd:\\workspace\\doc\\input.js',
resourceQuery: '',
issuer: '',
compiler: undefined
}
rule =>
{
rules:
[
{ resource: [Function: bound test], use: [Array] },
{ resource: [Function: bound test], use: [Array] },
{ resource: [Function: bound test], use: [Array] }
]
}
*/
_run = (data, rule, result) => {
// 判断特殊键提前返回
// test conditions
if (rule.resource && !data.resource)
return false;
if (rule.resourceQuery && !data.resourceQuery)
return false;
if (rule.compiler && !data.compiler)
return false;
if (rule.issuer && !data.issuer)
return false;
if (rule.resource && !rule.resource(data.resource))
return false;
if (data.issuer && rule.issuer && !rule.issuer(data.issuer))
return false;
if (data.resourceQuery && rule.resourceQuery && !rule.resourceQuery(data.resourceQuery))
return false;
if (data.compiler && rule.compiler && !rule.compiler(data.compiler))
return false; // ['rules'] => []
// apply
const keys = Object.keys(rule).filter((key) => {
return ["resource", "resourceQuery", "compiler", "issuer", "rules", "oneOf", "use", "enforce"].indexOf(key) < 0;
});
keys.forEach((key) => {
result.push({
type: key,
value: rule[key]
});
});
// 依次进入
if (rule.use) {
rule.use.forEach((use) => {
result.push({
type: "use",
value: typeof use === "function" ? RuleSet.normalizeUseItemFunction(use, data) : use,
enforce: rule.enforce
});
});
}
// 遍历3个判断标准
if (rule.rules) {
for (let i = 0; i < rule.rules.length; i++) {
this._run(data, rule.rules[i], result);
}
}
// 跳过
if (rule.oneOf) {
for (let i = 0; i < rule.oneOf.length; i++) {
if (this._run(data, rule.oneOf[i], result))
break;
}
} return true;
}

  这里会跳过部分代码,在配置文件的rules中我写了3个简单的loader,分别对应js、css、vue后缀的文件,入口文件为input.js,所以匹配到了babel-loader。

  获取到了对应的loader,继续跑流程:

// NormalModuleFactory的resolver事件流
this.plugin("resolver", () => (data, callback) => {
// ... asyncLib.parallel( /*...*/ , (err, results) => {
// ... /*
result =>
[
{
type: 'use',
value: { loader: 'babel-loader' },
enforce: undefined
}
]
*/
const result = this.ruleSet.exec({
resource: resourcePath,
resourceQuery,
issuer: contextInfo.issuer,
compiler: contextInfo.compiler
}); const settings = {};
const useLoadersPost = [];
const useLoaders = [];
const useLoadersPre = [];
result.forEach(r => {
if (r.type === "use") {
// enforce代表loader的特殊标记
if (r.enforce === "post" && !noPostAutoLoaders && !noPrePostAutoLoaders)
useLoadersPost.push(r.value);
else if (r.enforce === "pre" && !noPrePostAutoLoaders)
useLoadersPre.push(r.value);
// 走这条分支
else if (!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders)
useLoaders.push(r.value);
} else {
settings[r.type] = r.value;
}
});
// 又是parallel
asyncLib.parallel([
this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPost, this.resolvers.loader),
this.resolveRequestArray.bind(this, contextInfo, this.context, useLoaders, this.resolvers.loader),
this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPre, this.resolvers.loader)
], (err, results) => {
if (err) return callback(err);
loaders = results[0].concat(loaders, results[1], results[2]);
process.nextTick(() => {
callback(null, {
context: context,
request: loaders.map(loaderToIdent).concat([resource]).join("!"),
dependencies: data.dependencies,
userRequest,
rawRequest: request,
loaders,
resource,
resourceResolveData,
parser: this.getParser(settings.parser)
});
});
});
});
});

  这里判断了loader是否存在特殊标记,然后将结果弹入对应的loader数组中。

  最后再次调用了asyncLib的parallel方法,方法在上一个parallel调用过,但是当初没有loader,这次有了。

  看起来就比较复杂,下一节再过。

  把resolveRequestArray过完,方法源码与参数如下:

/*
contextInfo => { issuer: '', compiler: undefined }
context => D:\workspace\doc
array => [ { loader: 'babel-loader' } ]
resolver => resolvers.loader
callback => undefined
*/
resolveRequestArray = (contextInfo, context, array, resolver, callback) => {
if (array.length === 0) return callback(null, []);
asyncLib.map(array, (item, callback) => {
// resolver.loader
resolver.resolve(contextInfo, context, item.loader, (err, result) => {
if (err && /^[^/]*$/.test(item.loader) && !/-loader$/.test(item.loader)) {
return resolver.resolve(contextInfo, context, item.loader + "-loader", err2 => {
if (!err2) {
err.message = err.message + "\n" +
"BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" +
` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` +
" see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed";
}
callback(err);
});
}
if (err) return callback(err); const optionsOnly = item.options ? {
options: item.options
} : undefined;
return callback(null, Object.assign({}, item, identToLoaderRequest(result), optionsOnly));
});
}, callback);
}

  这里的array只有一个元素,map方法中调用了resolver的resolve方法,似曾相识,就跟之前那个resolve方法一样,不过来源是resolvers.loader对象。

  再回顾一下定义:

compiler.resolvers.normal = ResolverFactory.createResolver(Object.assign({
fileSystem: compiler.inputFileSystem
}, options.resolve));
compiler.resolvers.context = ResolverFactory.createResolver(Object.assign({
fileSystem: compiler.inputFileSystem,
resolveToContext: true
}, options.resolve));
compiler.resolvers.loader = ResolverFactory.createResolver(Object.assign({
fileSystem: compiler.inputFileSystem
}, options.resolveLoader));

  可以看出,除去最后面那个options,调用的方法是一模一样的,而options.resolve与options.resolveLoader在默认情况下如下所示:

{
"resolve": {
"unsafeCache": true,
"modules": ["node_modules"],
"extensions": [".js", ".json"],
"mainFiles": ["index"],
"aliasFields": ["browser"],
"mainFields": ["browser", "module", "main"],
"cacheWithContext": false
},
"resolveLoader": {
"unsafeCache": true,
"mainFields": ["loader", "main"],
"extensions": [".js", ".json"],
"mainFiles": ["index"],
"cacheWithContext": false
}
}

  只是少了modules、aliasFileds,其他都是一样的,这两个参数并不会影响如前doResolve几节中所讲的流程。

  也就是说,这个方法相当于回到了第29节,从头开始跑一遍所有的事件流,最后解析出对应的路径。

  这里有一个不一样的地方,这个babel-loader并不是普通的文件类型,所以在doResolver的事件串流中,会走模块分支。

  又臭又长的过程就先暂时跳过了,下节再讲,最后返回babel-loader的入口文件路径如下所示:

[ { loader: 'D:\\workspace\\node_modules\\babel-loader\\lib\\index.js' } ]

  通过神奇的resolve方法找到了对应loader的入口文件,最后的代码结果如下:

asyncLib.parallel([
this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPost, this.resolvers.loader),
this.resolveRequestArray.bind(this, contextInfo, this.context, useLoaders, this.resolvers.loader),
this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPre, this.resolvers.loader)
], (err, results) => {
if (err) return callback(err);
loaders = results[0].concat(loaders, results[1], results[2]);
process.nextTick(() => {
callback(null, {
// 'D:\\workspace\\doc'
context: context,
// 'D:\\workspace\\node_modules\\babel-loader\\lib\\index.js!D:\\workspace\\doc\\input.js'
request: loaders.map(loaderToIdent).concat([resource]).join("!"),
// ...
dependencies: data.dependencies,
// 'D:\\workspace\\doc\\input.js'
userRequest,
// './input.js'
rawRequest: request,
// [ { loader: 'D:\\workspace\\node_modules\\babel-loader\\lib\\index.js' } ]
loaders,
// 'D:\\workspace\\doc\\input.js'
resource,
// ...
resourceResolveData,
parser: this.getParser(settings.parser)
});
});
});

  其中最后的parser一会再说,先讲讲这个callback。

  看webpack源码最大的痛苦就是函数嵌套太深,每一个callback都是噩梦,所以这个callback我也是找了很久很久。

  这个事件流的入口如下:

this.plugin("factory", () => (result, callback) => {
let resolver = this.applyPluginsWaterfall0("resolver", null); // Ignored
if (!resolver) return callback(); resolver(result, (err, data) => { /*...*/ })
})

  这里调用了tapable的方法返回了一个函数,然后再次调用该函数。

  而这个事件流的主心骨就是两个asyncLib.parallel,根本找不到哪里返回了东西,直到我看到了事件流的plugin:

this.plugin("resolver", () => (data, callback) => {
// ...
})

  没错,这里有两个箭头函数,先返回一个函数,下面的调用才是真正的执行。

  那就很明显了,process.nextTick是一个node内置的异步方法,类似于vue的$nextTick,作用就不多说了。

  callback对应的就是那个调用时的第二个参数,而最后返回的大对象就是data。

  简要看一下回调函数内容:

resolver(result, (err, data) => {
if (err) return callback(err); // Ignored
if (!data) return callback(); // direct module
if (typeof data.source === "function")
return callback(null, data); this.applyPluginsAsyncWaterfall("after-resolve", data, (err, result) => {
// ...
});
});

  对返回的结果做了简单的判断,然后触发了另外一个事件流。

  

  下一节完善webpack是如何根据babel-loader搜索到对应的模块入口文件的。

.34-浅析webpack源码之事件流make(3)的更多相关文章

  1. .23-浅析webpack源码之事件流compilation(1)

    正式开始跑编译,依次解析,首先是: compiler.apply( new JsonpTemplatePlugin(options.output), // start new FunctionModu ...

  2. .21-浅析webpack源码之事件流this-compilation

    上一节生成Compilation实例后,添加了一些属性,随后触发this-compilation事件流,如下: Compiler.prototype.newCompilation = (params) ...

  3. .27-浅析webpack源码之事件流make(2)

    上一节跑到了NormalModuleFactory模块,调用了原型方法create后,依次触发了before-rsolve.factory.resolver事件流,这节从resolver事件流开始讲. ...

  4. .26-浅析webpack源码之事件流make(1)

    compilation事件流中,依然只是针对细节步骤做事件流注入,代码流程如图: // apply => this-compilation // apply => compilation ...

  5. .24-浅析webpack源码之事件流compilation(2)

    下一个compilation来源于以下代码: compiler.apply(new EntryOptionPlugin()); compiler.applyPluginsBailResult(&quo ...

  6. .22-浅析webpack源码之事件流compilation总览

    呃,终于到了这地方-- newCompilation(params) { // ... this.applyPlugins("this-compilation", compilat ...

  7. .25-浅析webpack源码之事件流compilation(3)

    这一节跑下一批plugin. compiler.apply( new EnsureChunkConditionsPlugin(), new RemoveParentModulesPlugin(), n ...

  8. .37-浅析webpack源码之事件流make(4)

    赶紧完结这个系列咯,webpack4都已经出正式版了. 之前的代码搜索到js文件的对应loader,并添加到了对象中返回,流程如下: this.plugin("factory", ...

  9. 浅析libuv源码-node事件轮询解析(3)

    好像博客有观众,那每一篇都画个图吧! 本节简图如下. 上一篇其实啥也没讲,不过node本身就是这么复杂,走流程就要走全套.就像曾经看webpack源码,读了300行代码最后就为了取package.js ...

随机推荐

  1. 广搜 poj3278 poj1426 poj3126

    Catch That Cow Time Limit: 2000 MS Memory Limit: 65536 KB 64-bit integer IO format: %I64d , %I64u Ja ...

  2. C# DataGridView中单元格Cell改变事件

    DataGridView控件中的各种事件都无法直接响应Cell中内容的变化,包括KeyPress等事件,可以采用下面方法 private void dataGridViewBarcode_Editin ...

  3. 利用koa打造jsonp API

    概述 最近学习利用koa搭建API接口,小有所得,现在记录下来,供以后开发时参考,相信对其他人也有用. 就目前我所知道的而言,API有2种,一种是jsonp这种API,前端通过ajax来进行跨域请求获 ...

  4. 跟踪spring MVC的请求

    当我们点击一个超链接时,spring MVC在后台都做了些什么呢,今天就来看看后台都干了啥 首先需要在web.xml里配置一下:

  5. 基础I/O接口与操作

    C语言中的文件接口 1 打开文件 FILE * fopen(const char * path,const char * mode) 参数:path:文件路径 mode:打开文件的方式 返回值:成功返 ...

  6. mongodb的Snapshot 隔离级别(记住)

    Snapshot 隔离和 Row Version的工作模式 当启用Snapshot隔离级别时,每一个更新数据的操作都会在tempdb中存储该行的原始副本,术语叫作行版本(RowVersion),SQL ...

  7. alembic教程

    安装 pip install alembic 步骤 1.初始化 alembic 仓库 在终端中, cd 到你的项目目录中,然后执行命令 alembic init alembic ,创建一个名叫 ale ...

  8. CentOS 6(64-bit) + Nginx搭建静态文件服务器

    Nginx搭建静态文件服务器 使用命令打开Nginx配置文件: sudo vim /etc/nginx/conf.d/default.conf 将配置改为: server { ...... ..... ...

  9. 前端代码质量保障之代码review

    经验丰富的程序员和一般程序员之间的最大区别,不仅体现在解决问题的能力上, 还体现在日常代码的风格上.掌握一门技术可能需要几月,甚至几周就够了. 好的习惯风格养成却需数年. 团队成员之间需要合作,代码需 ...

  10. Web API 2 对于 Content-Length 要求严格

    最近在做一个工具,里面有一个发起http请求的操作,虽然工具不是用.NET写的,但是测试用服务器软件是.NET写的.在这里选择了ASP.NET MVC和Web API 2. 首先预定义Student与 ...