前几天有小伙伴和我聊天,谈到如今前端面试愈来愈难,动不动就是xxx原理,有没有看过xx源码之类的问题,前端
以后就问我应该怎么来学习如今主流框架的源码,因而有了这一篇文章.react
说到使用react那很简单 react 和reactdom 两个文件引入一下就ok,可是这两个文件是通过编译打包,咱们没法在里面进行断点调试或者console调试,webpack
因此想学习框架源码,第一步就要在本地运行源码这样才能在内部进行各类输出调试。git
好了闲话不说,直接开始正题github
在这里我选择用的的版本是16.10.0 ,web
获取方式固然是react的git仓库面试
建立完项目以后要修改源码以及webopack配置,须要 将‘旺旺大礼包’给解出来npm
npm run eject
resolve:{ ..., alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ // 'react-native': 'react-native-web', // Allows for better profiling with ReactDevTools // ...(isEnvProductionProfile && { // 'react-dom$': 'react-dom/profiling', // 'scheduler/tracing': 'scheduler/tracing-profiling', // }), // ...(modules.webpackAliases || {}), 'react': path.resolve(__dirname, '../src/react/packages/react'), 'react-dom': path.resolve(__dirname, '../src/react/packages/react-dom'), 'legacy-events': path.resolve(__dirname, '../src/react/packages/legacy-events'), 'shared': path.resolve(__dirname, '../src/react/packages/shared'), 'react-reconciler': path.resolve(__dirname, '../src/react/packages/react-reconciler'), }, }
错误处理
替换完成后,由于版本和编译的缘由会遇到各类错误,react-native
具体的错误类型与解决方式,在这里作一个简单的介绍babel
因此咱们须要安装 ==@babel/plugin-transform-flow-strip-types== 这个插件忽略类型检测
npm install @babel/plugin-transform-flow-strip-types -D
//在webpack.config.js的babel-loader中添加配置 { test: /\.(js|mjs|jsx|ts|tsx)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { customize: require.resolve( 'babel-preset-react-app/webpack-overrides' ), plugins: [ ..., [require.resolve('@babel/plugin-transform-flow-strip-types')] // 配置忽略flow类型检测 ], ... }
//添加如下代码 export * from './forks/ReactFiberHostConfig.dom';
const stringified = { 'process.env': Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {}), "__DEV__": true, "__PROFILE__": true, "__UMD__": true };
// react此时未export内容,直接从ReactSharedInternals拿值 // import React from 'react'; // 此时React为undefined // const ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; import ReactSharedInternals from '../react/src/ReactSharedInternals';
export default function invariant(condition, format, a, b, c, d, e, f) { if(condition) return ; throw new Error( 'Internal React error: invariant() is meant to be replaced at compile ' + 'time. There is no runtime version.', ); }
到此为止如今运行的react项目采用的使咱们下载导入的react16.10.0的源码,咱们就能够在源码里进行输出的错误调试
好比我在react/index.js源码 进行输出测试
'use strict'; const React = require('./src/React'); console.log('源码测试',React) // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. module.exports = React.default || React;
嫌弃本地测试环境配置太麻烦的话,各位小主能够直接从个人git项目上下拉我配置好的开发项目
npm install npm start
ReactSourceCodeAnalyze:
https://github.com/fchangjun/ReactSourceCodeAnalyze.git
若是感受这篇文章有用,请各位小主关注公众号,随手转发一下下.