Nextjs +タイプスクリプト+スタイルのコンポーネント
概要
1Add Typescript
2Install styled-components
3Apply globalStyle
4Bonus 1 - Absolute imports
5Bonus 2 - SSR with stylesheet rehydration
場合は、すべてのコードが失われるhttps://github.com/rffaguiar/setup-nextjs-typescript-styled-components
また、Twitterで私に到達することができます.
動きましょう!
あなたは、ちょうど次に学び始めました.jsオンhttps://nextjs.org/learn/basics/create-nextjs-app . 今すぐあなた自身であなたの素晴らしいアプリを構築を開始します.小さなチュートリアルでは、スタイルのコンポーネント、タイプスクリプト、またはグローバルスタイルを追加する方法を教えていませんでした.心配しないで、私はこれらの赤ちゃんのステップを聞かせてください.
注意:このセットアップでは、次のパッケージバージョンが使用されました
"dependencies": {
"next": "9.4.4",
"react": "16.13.1",
"react-dom": "16.13.1",
"styled-components": "^5.1.1"
},
"devDependencies": {
"@types/node": "^14.0.9",
"@types/react": "^16.9.35",
"babel-plugin-styled-components": "^1.10.7",
"typescript": "^3.9.3"
}
PHPスクリプトを追加する
Rename any of your .js to .tsx . Go ahead and rename your index.js to index.tsx and try to start your server. You will receive an error on CLI that you're trying to use Typescript but you don't have the necessary packages. Run:
npm install --save-dev typescript @types/react @types/node
When you start the server after the ts packages, 2 files are created for you: next-env.d.ts
and tsconfig.json
.
-
next-env.d.ts
: Nextjs type declaration file referencing its types inside of your node_modules/next/types/global -
tsconfig.json
: contains the compiler options required to compile the project and specifies the root.
Your typescript is ready.
スタイルコンポーネントのインストール
npm install --save styled-components
For testing purposes, make your index.tsx
like this:
import styled from "styled-components";
const Title = styled.h1`
color: red;
`;
const Home = () => {
return (
<div>
<p>hello</p>
<Title>Title</Title>
</div>
);
};
export default Home;
Go to the browser and inspect the Title (h1) element.
クラス名がどれくらいひどいかについて見てください?
.sc-AxjAm.gxygnu
確かに記述的ではない!だからこそ、Babelプラグインをインストールすることをお勧めします.
npm install --save-dev babel-plugin-styled-components
ファイルを作る.babelrc
次のプロジェクトのルートで{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
サーバーを再起動し、再度要素を検査します.かなりクール、右?現在、クラス名はずっと記述的です.
Babelプラグインは、スタイルのコンポーネント+ nextjsにもっとパワーアップを与える
適用グローバルスタイル
Cool! Now you have an incredible JS framework with a powerful style system. But...wait, what if you wanted to reset and/or share styles across all of your pages? Here we go with styled-components' globalStyle
.
First, let's start with a Layout
component. This is going to wrap every page and has all the shared styles.
Outside the /pages
directory, create another folder /layout
with Basic.tsx
inside:
# /layout
# --/Basic.tsx
# /pages
# --/index.tsx
Inside of Basic.tsx
you include and return your shared styles. The trick here is to include the createGlobalStyle
and return it on Basic.tsx
render.
import { createGlobalStyle } from "styled-components";
export const GlobalStyle = createGlobalStyle`
// this is the shared style
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
h1 {
color: yellow !important; // the important is just to show that the style works!
}
// anything else you would like to include
`;
const BasicLayout = ({ children }: { children: any }) => {
return (
<>
<GlobalStyle />
{children}
</>
);
};
export default BasicLayout;
Returning to pages/index.tsx
. Import the newly created BasicLayout component and wrap the Home
returned React element with BasicLayout.
import styled from "styled-components";
import BasicLayout from "../layout/Basic";
const Title = styled.h1`
color: red;
`;
const Home = () => {
return (
<BasicLayout>
<p>hello</p>
<Title>Title</Title>
</BasicLayout>
);
};
export default Home;
From now on, all the pages that include BasicLayout
components are going to inherit the styles.
Congratulations!!! Now you have a proper Nextjs + Typescript + styled-component with global styles working!
ボーナス1-絶対輸入
By default Nextjs allows you to use relative imports. You know, those never-ending imports ../../../../finally.tsx
. If you want to use an absolute import, you have to change just one line on tsconfig.json
: the baseUrl
.
"compilerOptions": {
// other options
"baseUrl": "."
},
Now, all absolute imports start at the same level as the tsconfig.json
file. Using the previous pages/index.tsx
import as an example, you can change A to B.
// A
import BasicLayout from "../layout/Basic";
// B
import BasicLayout from "layout/Basic";
ボーナス2 -スタイルシートの再水和とSSR
The fancy term which means: serve the required styles for the first render within the HTML and then load the rest in the client.
You need to create a custom /pages/_document.tsx
and copy the following logic into it. That's it.
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
styled-components
example on nextjs github repo .Reference
この問題について(Nextjs +タイプスクリプト+スタイルのコンポーネント), 我々は、より多くの情報をここで見つけました https://dev.to/rffaguiar/nextjs-typescript-styled-components-1i3mテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol