react学习笔记1:创建react项目,通过Create React App创建单页面应用,创建服务器端渲染项目

蛰伏已久 蛰伏已久 2018-10-07

直接在页面中引用react.js

我们可以在项目文件中直接引入react.js,比如这样

<!DOCTYPE html>
<html>
  <head>
    <script src="../build/react.js"></script>
    <script src="../build/react-dom.js"></script>
    <script src="../build/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>

    
    <script type="text/babel">
      ReactDOM.render(
        <p>Hello, world!</p>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

创建单页面应用

如果我们需要创建单页面应用,则可以通过Create React App创建,只需3条命令即可

npx create-react-app my-app
cd my-app
npm start

创建服务器端渲染项目

通过Next.js创建服务器端渲染项目。

Next.js是一个流行的轻量级的react静态和服务器端渲染框架

官网:https://nextjs.org/learn/

Next.js is a popular and lightweight framework for static and server‑rendered applicationsbuilt with React.
It includes styling and routing solutions out of the box, 
and assumes that you’re using Node.js as the server environment.
#创建项目步骤
mkdir hello-next
cd hello-next
npm init -y
npm install --save react react-dom next
mkdir pages

打开package.json,加入如下内容

{
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  }
}

然后执行

npm run dev

打开:http://localhost:3000/

我的是404页面,提示“This page could not be found.”

原因是还没有一个页面,我们可以在pages下创建一个index.js,加入以下内容,可以看到页面可以正常访问了

const Index = () => (
  <div>
    <p>Hello Next.js</p>
  </div>
)

export default Index


创建静态的面向内容的(static content-oriented website)网站

Gatsby是创建react静态网站的最佳方式,它允许你使用react组件,但是输出预渲染的html和css文件,以确保最快的加载时间

官网:https://www.gatsbyjs.org/docs/

Gatsby is the best way to create static websites with React. 
It lets you use React components,
 but outputs pre-rendered HTML and CSS to guarantee the fastest load time.
npm install --global gatsby-cli

#创建一个新网站
gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-default

cd gatsby-site

gatsby develop   #Gatsby will start a hot-reloading development environment accessible at localhost:8000


gatsby build  #Gatsby will perform an optimized production build for your site generating static HTML and per-route JavaScript code bundles.

gatsby serve  #Gatsby starts a local HTML server for testing your built site.


参考文档:https://react.docschina.org/docs/create-a-new-react-app.html



分享到

点赞(0)