├── .prettierignore ├── example ├── .gitignore ├── src │ └── styles │ │ ├── index.css │ │ └── critical.css ├── next-env.d.ts ├── interfaces │ └── index.ts ├── components │ ├── ListDetail.tsx │ ├── ListItem.tsx │ ├── List.tsx │ └── Layout.tsx ├── next.config.js ├── pages │ ├── about.tsx │ ├── index.tsx │ ├── _document.tsx │ ├── initial-props.tsx │ └── detail.tsx ├── package.json ├── tsconfig.json ├── utils │ └── sample-api.ts └── README.md ├── src ├── index.tsx └── component.tsx ├── .prettierrc.json ├── .npmignore ├── tsconfig.json ├── LICENSE ├── package.json ├── .gitignore └── README.md /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .next 3 | -------------------------------------------------------------------------------- /example/src/styles/index.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | color: red; 3 | } -------------------------------------------------------------------------------- /example/src/styles/critical.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | color: red; 3 | } -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import CustomHead from "./component" 2 | 3 | export default CustomHead -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "semi": false, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /example/next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .prettierrc.json 2 | .prettierignores 3 | tsconfig.json 4 | tslint.json 5 | example/ 6 | src/ 7 | .idea/ -------------------------------------------------------------------------------- /example/interfaces/index.ts: -------------------------------------------------------------------------------- 1 | // You can include shared interfaces/types in a separate file 2 | // and then use them in any component by importing them. For 3 | // example, to import the interface below do: 4 | // 5 | // import User from 'path/to/interfaces'; 6 | 7 | export type User = { 8 | id: number 9 | name: string 10 | } 11 | -------------------------------------------------------------------------------- /example/components/ListDetail.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | 3 | import { User } from '../interfaces' 4 | 5 | type ListDetailProps = { 6 | item: User 7 | } 8 | 9 | const ListDetail: React.FunctionComponent = ({ 10 | item: user, 11 | }) => ( 12 |
13 |

Detail for {user.name}

14 |

ID: {user.id}

15 |
16 | ) 17 | 18 | export default ListDetail 19 | -------------------------------------------------------------------------------- /example/components/ListItem.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import Link from 'next/link' 3 | 4 | import { User } from '../interfaces' 5 | 6 | type Props = { 7 | data: User 8 | } 9 | 10 | const ListItem: React.FunctionComponent = ({ data }) => ( 11 | 12 | 13 | {data.id}: {data.name} 14 | 15 | 16 | ) 17 | 18 | export default ListItem 19 | -------------------------------------------------------------------------------- /example/next.config.js: -------------------------------------------------------------------------------- 1 | const withCSS = require('@zeit/next-css') 2 | /* Without CSS Modules, with PostCSS */ 3 | module.exports = withCSS() 4 | 5 | /* With CSS Modules */ 6 | // module.exports = withCSS({ cssModules: true }) 7 | 8 | /* With additional configuration on top of CSS Modules */ 9 | /* 10 | module.exports = withCSS({ 11 | cssModules: true, 12 | webpack: function (config) { 13 | return config; 14 | } 15 | }); 16 | */ 17 | -------------------------------------------------------------------------------- /example/components/List.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import ListItem from './ListItem' 3 | import { User } from '../interfaces' 4 | 5 | type Props = { 6 | items: User[] 7 | } 8 | 9 | const List: React.FunctionComponent = ({ items }) => ( 10 |
    11 | {items.map(item => ( 12 |
  • 13 | 14 |
  • 15 | ))} 16 |
17 | ) 18 | 19 | export default List 20 | -------------------------------------------------------------------------------- /example/pages/about.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import Link from 'next/link' 3 | import Layout from '../components/Layout' 4 | 5 | const AboutPage: React.FunctionComponent = () => ( 6 | 7 |

About

8 |

This is the about page

9 |

10 | 11 | Go home 12 | 13 |

14 |
15 | ) 16 | 17 | export default AboutPage 18 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "target": "esnext", 5 | "module": "commonjs", 6 | "lib": ["es6", "dom", "es2016", "es2017"], 7 | "skipLibCheck": true, 8 | "declaration": true, 9 | "noImplicitAny": true, 10 | "removeComments": true, 11 | "pretty": true, 12 | "jsx": "react", 13 | "rootDir": "./src", 14 | "outDir": "./dist" 15 | }, 16 | "exclude": ["node_modules"], 17 | "include": [ 18 | "./src/**/*.ts", 19 | "./src/**/*.tsx" 20 | ] 21 | } -------------------------------------------------------------------------------- /example/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import Link from 'next/link' 3 | import Layout from '../components/Layout' 4 | import { NextPage } from 'next' 5 | 6 | import '../src/styles/index.css' 7 | 8 | const IndexPage: NextPage = () => { 9 | return ( 10 | 11 |

Hello Next.js 👋

12 |

13 | 14 | About 15 | 16 |

17 |
18 | ) 19 | } 20 | 21 | export default IndexPage 22 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-typescript", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "dev": "next", 6 | "build": "next build", 7 | "start": "next start", 8 | "type-check": "tsc" 9 | }, 10 | "dependencies": { 11 | "@zeit/next-css": "^1.0.1", 12 | "next": "latest", 13 | "react": "^16.7.0", 14 | "react-dom": "^16.7.0" 15 | }, 16 | "devDependencies": { 17 | "@types/node": "^11.13.9", 18 | "@types/react": "^16.8.15", 19 | "@types/react-dom": "^16.0.11", 20 | "typescript": "3.5.2" 21 | }, 22 | "license": "ISC" 23 | } 24 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "alwaysStrict": true, 5 | "esModuleInterop": true, 6 | "forceConsistentCasingInFileNames": true, 7 | "isolatedModules": true, 8 | "jsx": "preserve", 9 | "lib": [ 10 | "dom", 11 | "es2017" 12 | ], 13 | "module": "esnext", 14 | "moduleResolution": "node", 15 | "noEmit": true, 16 | "noFallthroughCasesInSwitch": true, 17 | "noUnusedLocals": true, 18 | "noUnusedParameters": true, 19 | "resolveJsonModule": true, 20 | "skipLibCheck": true, 21 | "strict": true, 22 | "target": "esnext" 23 | }, 24 | "exclude": [ 25 | "node_modules" 26 | ], 27 | "include": [ 28 | "**/*.ts", 29 | "**/*.tsx" 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /example/pages/_document.tsx: -------------------------------------------------------------------------------- 1 | import Document, { Html, Head, Main, NextScript } from 'next/document' 2 | import CustomHead from '../../dist/component' 3 | import { readFileSync } from 'fs' 4 | import * as React from 'react' 5 | 6 | let styleSheetContent: string = '' 7 | 8 | export default class MyDocument extends Document { 9 | // @ts-ignore 10 | static async getInitialProps(ctx) { 11 | const initialProps = await Document.getInitialProps(ctx) 12 | 13 | const filePath = `./src/styles/critical.css` 14 | styleSheetContent = readFileSync(filePath, 'utf8') 15 | 16 | return { ...initialProps } 17 | } 18 | 19 | render() { 20 | const PreloadCssHead = CustomHead(Head, styleSheetContent) 21 | 22 | return ( 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | ) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /example/utils/sample-api.ts: -------------------------------------------------------------------------------- 1 | import { User } from '../interfaces' 2 | 3 | /** Dummy user data. */ 4 | export const dataArray: User[] = [ 5 | { id: 101, name: 'Alice' }, 6 | { id: 102, name: 'Bob' }, 7 | { id: 103, name: 'Caroline' }, 8 | { id: 104, name: 'Dave' }, 9 | ] 10 | 11 | /** 12 | * Calls a mock API which finds a user by ID from the list above. 13 | * 14 | * Throws an error if not found. 15 | */ 16 | export async function findData(id: number | string) { 17 | const selected = dataArray.find(data => data.id === Number(id)) 18 | 19 | if (!selected) { 20 | throw new Error('Cannot find user') 21 | } 22 | 23 | return selected 24 | } 25 | 26 | /** Calls a mock API which returns the above array to simulate "get all". */ 27 | export async function findAll() { 28 | // Throw an error, just for example. 29 | if (!Array.isArray(dataArray)) { 30 | throw new Error('Cannot find users') 31 | } 32 | 33 | return dataArray 34 | } 35 | -------------------------------------------------------------------------------- /example/components/Layout.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import Link from 'next/link' 3 | import Head from 'next/head' 4 | 5 | type Props = { 6 | title?: string 7 | } 8 | 9 | const Layout: React.FunctionComponent = ({ 10 | children, 11 | title = 'This is the default title', 12 | }) => ( 13 |
14 | 15 | {title} 16 | 17 | 18 | 19 |
20 | 33 |
34 | {children} 35 |
36 |
37 | I'm here to stay (Footer) 38 |
39 |
40 | ) 41 | 42 | export default Layout 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Takuto Tanako 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /example/pages/initial-props.tsx: -------------------------------------------------------------------------------- 1 | import { NextPage } from 'next' 2 | import Link from 'next/link' 3 | import Layout from '../components/Layout' 4 | import List from '../components/List' 5 | import { User } from '../interfaces' 6 | import { findAll } from '../utils/sample-api' 7 | 8 | type Props = { 9 | items: User[] 10 | pathname: string 11 | } 12 | 13 | const WithInitialProps: NextPage = ({ items, pathname }) => ( 14 | 15 |

List Example (as Function Component)

16 |

You are currently on: {pathname}

17 | 18 |

19 | 20 | Go home 21 | 22 |

23 |
24 | ) 25 | 26 | WithInitialProps.getInitialProps = async ({ pathname }) => { 27 | // Example for including initial props in a Next.js function compnent page. 28 | // Don't forget to include the respective types for any props passed into 29 | // the component. 30 | const items: User[] = await findAll() 31 | 32 | return { items, pathname } 33 | } 34 | 35 | export default WithInitialProps 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "next-critical", 3 | "version": "0.1.0", 4 | "description": "Custom Header for embed Critical CSS with Next.js", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "scripts": { 8 | "build": "rm -rf dist/ && tsc", 9 | "test": "echo \"Error: no test specified\" && exit 1" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/t09tanaka/next-critical.git" 14 | }, 15 | "keywords": [ 16 | "nextjs", 17 | "react", 18 | "critical css", 19 | "hoc", 20 | "high order component" 21 | ], 22 | "author": "Takuto Tanaka ", 23 | "license": "MIT", 24 | "bugs": { 25 | "url": "https://github.com/t09tanaka/next-critical/issues" 26 | }, 27 | "homepage": "https://github.com/t09tanaka/next-critical#readme", 28 | "devDependencies": { 29 | "@types/next": "^8.0.6", 30 | "@types/react": "^16.9.2", 31 | "next": "^9.0.5", 32 | "prettier": "^1.18.2", 33 | "react": "^16.9.0", 34 | "typescript": "^3.6.2" 35 | }, 36 | "engines": { 37 | "node": ">= 8.0.0" 38 | }, 39 | "peerDependencies": { 40 | "next": "^9.0.5", 41 | "react": "^16.9.0" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | # dependencies 64 | package-lock.json 65 | 66 | # Editor 67 | .idea/ 68 | 69 | # dist 70 | dist/ 71 | example/**/*.js -------------------------------------------------------------------------------- /example/pages/detail.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import { NextPageContext } from 'next' 3 | import Layout from '../components/Layout' 4 | import { User } from '../interfaces' 5 | import { findData } from '../utils/sample-api' 6 | import ListDetail from '../components/ListDetail' 7 | 8 | type Props = { 9 | item?: User 10 | errors?: string 11 | } 12 | 13 | class InitialPropsDetail extends React.Component { 14 | static getInitialProps = async ({ query }: NextPageContext) => { 15 | try { 16 | const { id } = query 17 | const item = await findData(Array.isArray(id) ? id[0] : id) 18 | return { item } 19 | } catch (err) { 20 | return { errors: err.message } 21 | } 22 | } 23 | 24 | render() { 25 | const { item, errors } = this.props 26 | 27 | if (errors) { 28 | return ( 29 | 30 |

31 | Error: {errors} 32 |

33 |
34 | ) 35 | } 36 | 37 | return ( 38 | 41 | {item && } 42 | 43 | ) 44 | } 45 | } 46 | 47 | export default InitialPropsDetail 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Next Critical⚡ 2 | 3 | Next Critical is a plug in that improve your web site speed with Critical CSS. 4 | 5 | ## How to use 6 | 7 | Install: 8 | 9 | ``` 10 | npm i -S next-critical 11 | ``` 12 | 13 | Create custom head component with your Critical CSS in _document.js. 14 | 15 | ```typescript:_document.tsx 16 | import Document, { Html, Head, Main, NextScript } from 'next/document' 17 | import CustomHead from 'next-critical' 18 | import { readFileSync } from 'fs' 19 | import * as React from 'react' 20 | 21 | let styleSheetContent: string = '' 22 | 23 | export default class MyDocument extends Document { 24 | // @ts-ignore 25 | static async getInitialProps(ctx) { 26 | const initialProps = await Document.getInitialProps(ctx) 27 | 28 | // Your critical css file 29 | const filePath = `./src/styles/critical.css` 30 | styleSheetContent = readFileSync(filePath, 'utf8') 31 | 32 | return { ...initialProps } 33 | } 34 | 35 | render() { 36 | const CriticalCssHead = CustomHead(Head, styleSheetContent) 37 | 38 | return ( 39 | 40 | 41 | 42 |
43 | 44 | 45 | 46 | ) 47 | } 48 | } 49 | ``` 50 | 51 | #### Related links 52 | 53 | [zeit/next.js](https://github.com/zeit/next.js) - Framework for server-rendered React applications -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # TypeScript Next.js example 2 | 3 | This is a really simple project that show the usage of Next.js with TypeScript. 4 | 5 | ## How to use it? 6 | 7 | ### Using `create-next-app` 8 | 9 | Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example: 10 | 11 | ```bash 12 | npx create-next-app --example with-typescript with-typescript-app 13 | # or 14 | yarn create next-app --example with-typescript with-typescript-app 15 | ``` 16 | 17 | ### Download manually 18 | 19 | Download the example: 20 | 21 | ```bash 22 | curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-typescript 23 | cd with-typescript 24 | ``` 25 | 26 | Install it and run: 27 | 28 | ```bash 29 | npm install 30 | npm run dev 31 | # or 32 | yarn 33 | yarn dev 34 | ``` 35 | 36 | ## The idea behind the example 37 | 38 | This example shows how to integrate the TypeScript type system into Next.js. Since TypeScript is supported out of the box with Next.js, all we have to do is to install TypeScript. 39 | 40 | ``` 41 | npm install --save-dev typescript 42 | ``` 43 | 44 | To enable TypeScript's features, we install the type declaratons for React and Node. 45 | 46 | ``` 47 | npm install --save-dev @types/react @types/react-dom @types/node 48 | ``` 49 | 50 | When we run `next dev` the next time, Next.js will start looking for any `.ts` or `.tsx` files in our project and builds it. It even automatically creates a `tsconfig.json` file for our project with the recommended settings. 51 | 52 | Next.js has built-in TypeScript declarations, so we'll get autocompletion for Next.js' modules straight away. 53 | 54 | A `type-check` script is also added to `package.json`, which runs TypeScript's `tsc` CLI in `noEmit` mode to run type-checking separately. You can then include this, for example, in your `test` scripts. 55 | -------------------------------------------------------------------------------- /src/component.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | import { Head } from 'next/document' 3 | 4 | const CustomHead = ( 5 | WrappedComponent: typeof Head, 6 | styleSheetContent: string 7 | ): typeof Head => { 8 | // @ts-ignore 9 | return class extends WrappedComponent { 10 | constructor(props: any) { 11 | super(props) 12 | } 13 | 14 | getCssLinks() { 15 | // @ts-ignore 16 | const { assetPrefix, files } = this.context._documentProps 17 | if (!files || files.length === 0) { 18 | return null 19 | } 20 | 21 | const hasCssFiles = files.find(file => /\.css$/.exec(file)) 22 | 23 | let isFirst = true 24 | 25 | if(hasCssFiles){ 26 | return files.map((file: string, index: number) => { 27 | // Only render .css files here 28 | if (!/\.css$/.exec(file)) { 29 | return null 30 | } 31 | 32 | // @ts-ignore 33 | return ( 34 | 35 | {isFirst && ( 36 |