在浏览器中编译运行 React
· 阅读需 7 分钟
一直很好奇 React 官网的在线编辑器是如何实现的,于是稍微研究了一下,通过 TypeScript 和 Babel 实现在浏览器中编译 React。
这个项目本身也 是使用 TypeScript, Webpack 和 Babel 构建的,源码在 react-online - Skyone Git。
在开始之前,请确保你了解了 React 的代码如何从 TSX 格式转换为浏览器可以执行的 JavaScript 代码,如果不了解,可以参考 TypeScript 官网 和 Babel 官网。当然,打包工具 Webpack 也必须要了解。
项目结构
由于整个程序就一个页面,没有路由等麻烦事,所以就按最简单的方式来实现。
项目结构差不多是这样的:
├── src
│ ├── index.ts
│ └── style.css
├── public
├── scripts
└── package.json
直到最后,我用到了如下依赖:
{
"devDependencies": {
"@babel/core": "^7.23.6",
"@babel/preset-env": "^7.23.6",
"@codemirror/commands": "^6.3.2",
"@codemirror/lang-javascript": "^6.2.1",
"@codemirror/language": "^6.9.3",
"@codemirror/view": "^6.22.3",
"@types/node": "^20.10.5",
"@types/webpack-env": "^1.18.4",
"@uiw/codemirror-theme-github": "^4.21.21",
"autoprefixer": "^10.4.16",
"babel-loader": "^9.1.3",
"clean-webpack-plugin": "^4.0.0",
"codemirror": "^6.0.1",
"copy-webpack-plugin": "^11.0.0",
"cross-env": "^7.0.3",
"css-loader": "^6.8.1",
"css-minimizer-webpack-plugin": "^5.0.1",
"html-webpack-plugin": "^5.6.0",
"mini-css-extract-plugin": "^2.7.6",
"postcss": "^8.4.32",
"postcss-loader": "^7.3.3",
"style-loader": "^3.3.3",
"tailwindcss": "^3.4.0",
"terser-webpack-plugin": "^5.3.9",
"ts-loader": "^9.5.1",
"typescript": "^5.3.3",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"webpack-merge": "^5.10.0",
"webpackbar": "^6.0.0"
}
}