基于本地JS文件搭建
demo.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>React Demo</title>
</head>
<body><!-- 创建根节点 --><div id="root"></div><!-- 引入React18的依赖 --><script src="./static/react18.3.1/react.development.js"></script><script src="./static/react18.3.1/react-dom.development.js"></script><!-- 核心代码 --><script>// 创建一个组件function LikeButton(){return React.createElement("button", {onClick: () => {console.log("Like button is clicked")}}, "Clike Me")}// 渲染组件const rootNode = document.getElementById("root")const root = ReactDOM.createRoot(rootNode);root.render(React.createElement(LikeButton))</script>
</body>
</html>
通过nvm搭建NodeJS环境
安装nvm
下载:https://github.com/coreybutler/nvm-windows/releases
一直下一步安装。
使用nvm管理nodejs
安装:
nvm install 18
切换nodejs版本:
nvm use 18
配置国内镜像
npm config set registry https://registry.npmmirror.com
配置全局目录
手动在nvm安装目录下创建cache和global两个目录,然后执行配置:
npm config set prefix "D:\web\nvm\global"
npm config set cache "D:\web\nvm\cache"
将global目录添加到环境变量
将D:\web\nvm\global添加到环境变量的Path路径下。
这一步很重要,因为我们全局安装的可执行文件会被存放在这个目录中,如果不配置,全局安装的可执行文件会找不到,就会报错。
全局安装yarn
安装yarn:
npm install -g yarn
基于文件创建React18项目
package.json
{"name": "frontend","version": "0.1.0","private": true,"dependencies": {"react": "^18.2.0","react-dom": "^18.2.0","react-scripts": "5.0.1","web-vitals": "^2.1.4"},"scripts": {"start": "react-scripts start","build": "react-scripts build"},"browserslist": {"production": [">0.2%","not dead","not op_mini all"],"development": ["last 1 chrome version","last 1 firefox version","last 1 safari version"]}
}
public/index.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<React.StrictMode><App /></React.StrictMode>
);
src/App.js
function App() {return (<div className="App">你好,张大鹏,这是React18开发的界面</div>);
}export default App;
启动
npm install -g yarn
yarn
yarn start