次への代替案の導入js
40640 ワード
導入
我々は反応アプリを開発するときは、サーバーとクライアントを分離するための最良の選択肢の一つです.
しかし、それらの場合では、サーバー側でクライアントのためにそれほど多くの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を反応させる
概要
props
props
process.env.NODE_ENV !== 'production'
賛否両論
長所
ビューテンプレートエンジンだけですので
.hbs
, .ejs
と反応.(ts|js)x
短所
用途
@反応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:
-
@react-ssr/core
- A core package for
@react-ssr/express
and@react-ssr/nestjs-express
- A core package for
-
@react-ssr/express
- A package for pure Express applications
-
@react-ssr/nestjs-express
- A package for NestJS 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
.tsx
@反応SSR/NESTJS急行
センド/スタティック
.jsx
.tsx
例/ JSX AND
例/ JSXエモーション
JSX素材の使用例
例/ JSXセマンティックUI
例/ JSXスタイルコンポーネント
結論
してくださいreact-ssr フィードバックを送ってください!
ベスト
Reference
この問題について(次への代替案の導入js), 我々は、より多くの情報をここで見つけました https://dev.to/saltyshiomix/introducing-an-alternative-to-next-js-12phテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol