createModuleIdFactory負(fù)責(zé)固定module的ID。在打包生成的jsbundle中,__d中定義的各個(gè)module后都有一個(gè)數(shù)字表示,并在最后的require方法中進(jìn)行調(diào)用,這其中的數(shù)字就是createModuleIdFactory方法生成的。如果添加了新的module,比如說引入了新的三方庫(kù),那么ID會(huì)重新生成。下面的實(shí)例代碼便是通過常規(guī)的package命令行代碼react-native bundle --platform ios --dev false --entry-file index.js --bundle-output build/ios/main.jsbundle --assets-dest build/ios/打包生成的main.jsbundle
// 全局函數(shù)和全局變量的定義,其中也包括了__d函數(shù)的定義
var __BUNDLE_START_TIME__=...
...
__d(function(...){},123,[]);
...
__d(function(a,s,t,e,n,r,u){n.exports={name:"statusbar",displayName:"statusbar"}},484,[]);
__r(82);
__r(0);
其中使用最多的就是這個(gè)__d函數(shù),每一個(gè)js module打包后都會(huì)對(duì)應(yīng)一個(gè)__d函數(shù),從頭部的全局函數(shù)定義中,可以把該函數(shù)分離出來:
__d = function (r, i, n) {
if (null != e[i]) return;
var o = {
dependencyMap: n,
factory: r,
hasError: !1,
importedAll: t,
importedDefault: t,
isInitialized: !1,
publicModule: { exports: {} }
};
e[i] = o
}
它由三個(gè)入?yún)?br>
r:js module的具體實(shí)現(xiàn);
i:當(dāng)前js module的Id
n:該js module所依賴的其他js module的Id
由這三個(gè)參數(shù),在配合其他的一些全局變量,構(gòu)建出了一個(gè)對(duì)象o,再把o綁在object e中,從此處可以看到i也就是這個(gè)Id必須是唯一的。
當(dāng)我們需要拆包時(shí),公共module的ID每次構(gòu)建時(shí)必須是固定的,因此0.56+版本的metro可以通過自定義createModuleIdFactory方法將基礎(chǔ)module的ID固定下來。
先來看看metro中該方法的實(shí)現(xiàn)metro/src/lib/createModuleIdFactory.js
'use strict';
function createModuleIdFactory(): (path: string) => number {
const fileToIdMap: Map<string, number> = new Map();
let nextId = 0;
return (path: string) => {
let id = fileToIdMap.get(path);
if (typeof id !== 'number') {
id = nextId++;
fileToIdMap.set(path, id);
}
return id;
};
}
module.exports = createModuleIdFactory;
這段代碼比較簡(jiǎn)單,很容易讀懂,參數(shù)path是module的路徑,比如node_modules/react-native/Libraries/Image/Image.ios.js。在函數(shù)內(nèi)部定義了兩個(gè)局部變量fileToIdMap和nextId,這兩個(gè)變量在一次打包時(shí)是被共享了,類似于static。每次調(diào)用時(shí),會(huì)先檢查fileToIdMap中是否已經(jīng)有這個(gè)路徑了,如果有,直接返回對(duì)應(yīng)的Id,如果沒有,nextId加一并將這個(gè)path存入map中,再返回Id。
可以使用module的相對(duì)路徑作為這個(gè)id,根據(jù)這個(gè)思路來提供自定義的createModuleIdFactory
'use strict';
const path = require('path');
const pathSep = path.posix.sep;
function createModuleIdFactory() {
const fileToIdMap = new Map();
const projectRootPath = `${process.cwd()}`;
return (path) => {
let moduleName = '';
if (path.indexOf(`node_modules${pathSep}react-native${pathSep}Libraries${pathSep}`) > 0) {
moduleName = path.substr(path.lastIndexOf(pathSep) + 1);
} else if (path.indexOf(projectRootPath) === 0) {
moduleName = path.substr(projectRootPath.length + 1);
}
moduleName = moduleName.replace('.js', '');
moduleName = moduleName.replace('.png', '');
let regExp = pathSep === '\\' ? new RegExp('\\\\', 'gm') : new RegExp(pathSep, 'gm');
moduleName = moduleName.replace(regExp, '_');
return moduleName;
};
}
module.exports = createModuleIdFactory;
其實(shí)可以直接使用path,但傳入的path參數(shù),是該module的絕對(duì)路徑,也就是說在path中有一個(gè)完全相同的前綴,所以此處將前綴去掉,而對(duì)于react-native的js module,由于路徑較深,這里也將它去掉:
if (path.indexOf(`node_modules${pathSep}react-native${pathSep}Libraries${pathSep}`) > 0) {
moduleName = path.substr(path.lastIndexOf(pathSep) + 1);
} else if (path.indexOf(projectRootPath) === 0) {
moduleName = path.substr(projectRootPath.length + 1);
}
自定義的createModuleIdFactory的使用方式:
react-native項(xiàng)目根目錄下有名為metro.config.js的配置文件,用于配置metro運(yùn)行參數(shù),我們需要定義的就是serializer下的createModuleIdFactory。
const createModuleIdFactory = require('./config/createModuleIdFactory');
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
serializer: {
createModuleIdFactory: createModuleIdFactory
}
};
配置好后,再次運(yùn)行react-native bundle --platform ios --dev false --entry-file index.js --bundle-output build/ios/main.jsbundle --assets-dest build/ios/,便是基于新的createModuleIdFactory來創(chuàng)建Id的。當(dāng)我們?cè)诖瞬榭创虬蟮膉sbundle文件時(shí),便會(huì)看到如下結(jié)果:
...
__d(
function (g, r, i, a, m, e, d) {
var t = r(d[0]);
Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0;
var o = t(r(d[1])), u = r(d[2]), n = u.StyleSheet.create({ image: { height: 24 } });
e.default = function (t) {
var c = t.routeName, l = t.focused, f = { Home: r(l ? d[3] : d[4]), My: r(l ? d[5] : d[6]) };
return o.default.createElement(u.Image, { style: n.image, source: f[c], resizeMode: "contain" })
}
},
"src_components_TabBarIcon_index",
[
"node_modules_@babel_runtime_helpers_interopRequireDefault",
"node_modules_react_index",
"react-native-implementation",
"src_assets_icons_home_fill",
"src_assets_icons_home",
"src_assets_icons_my_fill",
"src_assets_icons_my"
]
);
...
此時(shí),__d函數(shù)的第二第三個(gè)參數(shù)已經(jīng)替換成了module的路徑。