次への代替案の導入js


導入


我々は反応アプリを開発するときは、サーバーとクライアントを分離するための最良の選択肢の一つです.
しかし、それらの場合では、サーバー側でクライアントのためにそれほど多くのAPIを実装しなければなりません.
一方、ハンドルやEJSのようなサーバーをレンダリングするための良い古い方法は、単一のページのアプリやサーバー側のレンダリングアプリケーションに対応するために適していません.
次は使用できませんが.JSは、明示的なサーバからのようなビューテンプレートエンジンですが、このようなちょっとトリッキーなテクニックが必要です.
// pages/index.tsx

const IndexPage = ({ articles }) => {
  return (
    <ul>
      {articles.map((article, index) => (
        <li key={index}>{article.title}</li>
      ))}
    </ul>
  );
};

// we must use `getInitialProps()` to enable SSR correctly
IndexPage.getInitialProps = async ({ req, query }) => {
  const isServer = !!req;

  // and we have to check a process is a server or not
  let articles;
  if (isServer) {
    // if the server side, we can receive data from the server directly
    articles = query.articles;
  } else {
    // if the client side, we must fetch data from the API server
    articles = await http.get('api/articles');
  }

  // finally, we can use data in the `IndexPage` component like above
  return {
    articles,
  };
};
このような実装を考えたことがありますか?
// server.js

const express = require('express');

const app = express();

app.get('/', (req, res) => {
  const message = 'Hello World!';
  res.render('index', { message });
});

app.listen(3000, () => {
  console.log('> Ready on http://localhost:3000');
});
// views/index.jsx

export default function IndexPage{ message }) {
  return <p>{message}</p>;
}
そして、我々がSSRによって『Hello World』を見ることができるならば?

想像しましょう!


// server.js

const posts = [
  { id: 1, body: 'This is a first post.' },
  { id: 2, body: 'This is a second post.' },
  { id: 3, body: 'This is a last post.' },
];

app.get('/', (req, res) => {
  res.render('index', { posts });
});

app.get('/posts/:postId', (req, res) => {
  const { postId } = req.params;
  const post = findById(postId);
  res.render('post', { post });
});
// views/index.jsx

import React from 'react';

const IndexPage = ({ posts }) => {
  return (
    <React.Fragment>
      {posts.map((post, index) => {
        return (
          <p key={index}>
            <a href={'/posts/' + post.id}>{post.body}</a>
          </p>
        );
      })}
    </React.Fragment>
  );
};

export default IndexPage;
// views/post.jsx

import React from 'react';

const PostPage = ({ post }) => {
  return (
    <React.Fragment>
      <p>{post.body}</p>
    </React.Fragment>
  );
};

export default PostPage;
それは十分に簡単ですか?
そして、我々は、それがビューテンプレートエンジンであるかのように反応を使用することができます!

反応SSRについて


サルティシミックス / 反応する


ビューテンプレートエンジンとしてSSRを反応させる


概要

  • ビューテンプレートエンジンとしてのSSR
  • ダイナミックprops
  • サーバーデータを反応クライアントに渡すprops
  • 適切な
  • 管理パネル
  • ブログ
  • 開発者経験
  • WebpackとBabelのゼロ設定
  • HMR(Home Model Replace)両方のスクリプトとスタイルであってもprocess.env.NODE_ENV !== 'production'
  • 組み込みSASS ( SCSS )サポート
  • 賛否両論


    長所


    ビューテンプレートエンジンだけですので
  • これはAPIを持っている必要はありません、我々がしなければならないすべては、サーバーデータをクライアントに渡すことです
  • このような複数のエンジンをサポート.hbs , .ejs と反応.(ts|js)x
  • 私たちはpassport 常に認証
  • 短所

  • 各リクエストに対してHTML全体をアセンブルするので、それはそうではありません
  • クライアント側ルーティングをサポートしません
  • 用途


    @反応SSR /急行で


    インストール
    $ npm install --save @react-ssr/core @react-ssr/express express react react-dom

    And add a script to your package.json like this:

    概要

    • Pass the server data to the React client props
      • So it reacts as if it is a view template engine
      • Off course, it is optimized for search engines by using server side rendering
    • Developer Experience
      • It is so easy to use and there is almost nothing to learn the way to use
      • HMR (Hot Module Replacement) when process.env !== 'production'

    反応SSRを使う方法

    There are three npm packages for Express applications:

    JavaScriptでの@ RESERT SSR / Expressの使用法

    Installation:

    $ npm install --save @react-ssr/core @react-ssr/express express react react-dom
    
    package.json :
    {
      "scripts": {
        "start": "node server.js"
      }
    }
    
    プロジェクト内のファイルを次のように入力します..babelrc :
    {
      "presets": [
        "@react-ssr/express/babel"
      ]
    }
    
    server.js :
    const express = require('express');
    const register = require('@react-ssr/express/register');
    
    const app = express();
    
    (async () => {
      // register `.jsx` as a view template engine
      await register(app);
    
      app.get('/', (req, res) => {
        const message = 'Hello World!';
        res.render('index', { message });
      });
    
      app.listen(3000, () => {
        console.log('> Ready on http://localhost:3000');
      });
    })();
    
    ビュー/インデックス.日本学術振興会
    export default function IndexPage({ message }) {
      return <p>{message}</p>;
    }
    
    それだ!
    それからちょうど実行npm start そして、http://localhost:3000 , あなたはHello World! .

    を使用して@反応スクリプト/エクスプレス


    TypeScriptエンジンを有効にするには.tsx ), ジャストプットtsconfig.json プロジェクトのルートディレクトリにあります.
    タイプスクリプトのコードは次のようになります.package.json :
    {
      "scripts": {
        "start": "ts-node server.ts"
      }
    }
    
    server.ts :
    import express, { Request, Response } from 'express';
    import register from '@react-ssr/express/register';
    
    const app = express();
    
    (async () => {
      // register `.tsx` as a view template engine
      await register(app);
    
      app.get('/', (req: Request, res: Response) => {
        const message = 'Hello World!';
        res.render('index', { message });
      });
    
      app.listen(3000, () => {
        console.log('> Ready on http://localhost:3000');
      });
    })();
    
    views/index.tsx :
    interface IndexPageProps {
      message: string;
    }
    
    export default function IndexPage({ message }: IndexPageProps) {
      return <p>{message}</p>;
    }
    

    @ RESET SSR / NESTJS Expressの使用法


    インストール
    # install NestJS dependencies
    $ npm install --save @nestjs/core @nestjs/common @nestjs/platform-express
    
    # install @react-ssr/nestjs-express
    $ npm install --save @react-ssr/core @react-ssr/nestjs-express react react-dom
    
    package.json :
    {
      "scripts": {
        "start": "ts-node --project tsconfig.server.json server/main.ts"
      }
    }
    
    次に、プロジェクトの内部にあるファイルを入力します..babelrc :
    {
      "presets": [
        "@react-ssr/nestjs-express/babel"
      ]
    }
    
    tsconfig.json :
    {
      "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "node",
        "jsx": "preserve",
        "lib": [
          "dom",
          "dom.iterable",
          "esnext"
        ],
        "strict": true,
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true
      },
      "exclude": [
        "node_modules",
        "ssr.config.js",
        ".ssr"
      ]
    }
    
    tsconfig.server.json :
    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "module": "commonjs"
      },
      "include": [
        "server"
      ]
    }
    
    server/main.ts :
    import { NestFactory } from '@nestjs/core';
    import { NestExpressApplication } from '@nestjs/platform-express';
    import register from '@react-ssr/nestjs-express/register';
    import { AppModule } from './app.module';
    
    (async () => {
      const app = await NestFactory.create<NestExpressApplication>(AppModule);
    
      // register `.tsx` as a view template engine
      await register(app);
    
      app.listen(3000, async () => {
        console.log(`> Ready on http://localhost:3000`);
      });
    })();
    
    server/app.module.ts :
    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    
    @Module({
      controllers: [
        AppController,
      ],
    })
    export class AppModule {}
    
    server/app.controller.ts :
    import {
      Controller,
      Get,
      Render,
    } from '@nestjs/common';
    
    @Controller()
    export class AppController {
      @Get()
      @Render('index') // this will render `views/index.tsx`
      public showHome() {
        const user = { name: 'NestJS' };
        return { user };
      }
    }
    
    最後に、ビュー/インデックス.TSX :
    interface IndexPageProps {
      user: any;
    }
    
    const IndexPage = ({ user }: IndexPageProps) => {
      return <p>Hello {user.name}!</p>;
    };
    
    export default IndexPage;
    
    その後、ちょうど実行npm start そして、http://localhost:3000なるほどHello NestJS! .

    例が多い


  • @反応SSR/急行
  • .jsx
  • examples/basic-jsx
  • examples/basic-custom-views
  • examples/basic-custom-document
  • examples/basic-dynamic-head
  • examples/basic-hmr-css
  • examples/basic-hmr-scss
  • examples/basic-blogging
  • examples/with-jsx-antd
  • examples/with-jsx-bulma
  • examples/with-jsx-emotion
  • examples/with-jsx-material-ui
  • examples/with-jsx-semantic-ui
  • examples/with-jsx-styled-components
  • .tsx
  • examples/basic-tsx

  • @反応SSR/NESTJS急行
  • examples/basic-nestjs
  • examples/basic-nestjs-nodemon

  • センド/スタティック
  • .jsx
  • examples/basic-jsx-static
  • examples/with-jsx-static-bulma
  • .tsx
  • examples/basic-tsx-static
  • 例/ JSX AND



    例/ JSXエモーション



    JSX素材の使用例



    例/ JSXセマンティックUI



    例/ JSXスタイルコンポーネント



    結論


    してくださいreact-ssr フィードバックを送ってください!
    ベスト