博主这周开始学react 一早上敲了helloworld 开心 原地转圈圈
- 先建一个文件夹叫它react-demo
src/App.js
import React from 'react';
export default function App() {
return <h1> hello world</h1>;
}
- 在node.js中renderToString()方法将组件渲染成字符串
src/sever.js
import React from 'react';
import { renderToString} from 'react-dom/server';
import App from './App';
const appHtml=renderToString(<App/>);
console.log(appHtml);
index.js
require('babel-register');
require('./src/server');
.babelrc
{"presets": ["react","es2015"]}
js文件就这么多
在命令行运行
- 接下来 npm install 会生成一个 package-lock.json 文件
npm WARN saveError ENOENT: no such file or directory, open 'E:\react demo\node下运行react\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'E:\react demo\node下运行react\package.json'
但是呢你发现没有package.json 文件 what????
伤心 那就手动 生成 npm init ok 终于有package.json 文件喽
- 用Babel 编译运行node.js 使用requie Hook
安装babel -register
npm install babel-register --save-dev
- 安装ES2015和React的预设
npm install --save-dev babel-preset-es2015 babel-preset-react
这个时候点开package.json文件会发现多了好多东西 amazing
{
"name": "",
"version": "",
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.26.0"
},
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0"
}
}
好吧都是刚才装上的东西
- 这个时候就可以 npm start 激动
但是emmm。。。
E:\react demo\node下运行react>npm start
npm ERR! missing script: start
找不到 start 好吧
package.json文件加两行代码
{
"name": "",
"version": "",
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.26.0"
},
"scripts": {
"start": "node index"
},
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0"
}
}
emmm..... npm start 还是有问题
Error: Cannot find module 'react'
npm install react
Error: Cannot find module 'react-dom/server'
npm install react-dom
*最后 npm start