Next.js 9でSSR
はじめに
ReactでSSR(Server Side Rendering)フレームワークとしてNext.jsは有名です。
Next.jsの新しい特性
- Built-in Zero-Config TypeScript Support: Build your application with increased confidence, thanks to automatic TypeScript support and integrated type-checking.
- File system-Based Dynamic Routing: Express complex application routing requirements through the file system without the need for a custom server.
- Automatic Static Optimization: Create ultra-fast websites that leverage Server-Side Rendering and Static Prerendering by default without compromising on features.
- API Routes: Quickly build back-end application endpoints, leveraging hot-reloading and a unified build-pipeline.
- More Production Optimizations: Applications are more responsive than ever thanks to in-viewport prefetching and other optimizations.
- Improved DX: Unobtrusive, ease-of-use improvements to help you develop at your best.
出典:https://nextjs.org/blog/next-9
デモプロジェクト作成してみる
インストール
フォルダー「nextjs-demo」を作成し、npm init
を実行後、npm install --save next react react-dom
を実行
package.jsonファイル修正
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
pagesフォルダーにファイル作成
./pages/index.jsファイルに
function Home() {
return <div>ようこそ。</div>
}
export default Home
next.js起動
npm run dev
アクセス
これで一番シンプルのページができました。
Typescriptに変更
npm install --save-dev typescript @types/react @types/node
mv pages/index.js pages/index.tsx
npm run dev
これでTypescript形式でもアクセスできます。
typescriptも自動インストールのようですが、私のPCはエラーがあって手動でインストールしました。
Router
Next.jsはpagesディレクトリのファイル、サブディレクトリのファイルをアクセスできます。
URLのpathにパラメータを渡したい場合は、正規表現の感じで動的にマッピングする必要があります。
このニーズでも問題ありません。
express.jsではよくある「/xxx/:id」の形式は、next.jsは「pages/xxx/[id].js」を作成して対応できます。
サンプル: /mypage/:userId
pagesディレクトリに「mypage」フォルダーを作成し、「mypage」の中で「[userId].js」のファイルを作成
import React from 'react';
class MyPage extends React.Component {
static async getInitialProps({ query }) {
const { userId } = query
return { userId }
}
constructor(props) {
super(props);
this.state = {
userId: props.userId
}
}
render() {
return (
<div>
URLのPathからuserId: {this.state.userId}
</div>
)
}
}
export default MyPage
アクセス
[userId].jsのコードの結果を正しく表示されました。
これでURLとファイルの作成はもっと理解しやすくなります。
簡単にデモをやってみました。
以上
Author And Source
この問題について(Next.js 9でSSR), 我々は、より多くの情報をここで見つけました https://qiita.com/chenglin/items/8d37bf38750e72ac39c9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .