Commit 5496e0f8 authored by Jakub Karabuła-Stysiak's avatar Jakub Karabuła-Stysiak Committed by Luis Alvarez D

Add electron typescript example (#8682)

* Add initial Electron-Typescript-Next example

* Move and add types

* Update readme

* Update renderer

* remove config
parent a5ebe41a
# Electron with Typescript application example
**You can find a detailed documentation about how to build Electron apps with Next.js [here](https://leo.im/2017/electron-next)!**
## How to use
### Using `create-next-app`
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:
```bash
npx create-next-app --example with-electron-typescript with-electron-typescript-app
# or
yarn create next-app --example with-electron-typescript with-electron-typescript-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-electron-typescript
cd with-electron-typescript
```
To install and start dev build:
```bash
yarn install && yarn build && yarn start
```
Available commands:
```bash
"yarn build-renderer": build and transpile Next.js layer
"yarn build-electron": transpile electron layer
"yarn build": build both layers
"yarn start": start dev version
"yarn dist": create production elctron build
"yarn type-check": check TypeScript in project
```
## The idea behind the example
This example show how you can use Next.js inside an Electron application to avoid a lot of configuration, use Next.js router as view and use server-render to speed up the initial render of the application. Both Next.js and Electron layers are written in TypeScript and compiled to JavaScript during the build process.
| Part| Source code (Typescript) | Builds (JavaScript) |
| -- | -- | -- |
| Next.js | `/renderer` | `/renderer` |
| Electron | `/electron-src` | `/main` |
| Production | | `/dist` |
For development it's going to run a HTTP server and let Next.js handle routing. In production it use `next export` to pre-generate HTML static files and use them in your app instead of running an HTTP server.
You can create the production app using `npm run dist`.
_note regarding types:_
* Electron provides its own type definitions, so you don't need @types/electron installed!
source: https://www.npmjs.com/package/@types/electron
* There were no types available for `electron-next` at the time of creating this example, so until they are available there is a file `electron-next.d.ts` in `electron-src` directory.
declare module "electron-next" {
function adjustRenderer (directory: string): void;
function devServer (dir: string, port?: number): void;
interface Directories {
production: string,
development: string
}
export default function(directories: Directories | string, port?: number): adjustRenderer | devServer;
}
\ No newline at end of file
// Native
import { join } from 'path'
import { format } from 'url'
// Packages
import { BrowserWindow, app, ipcMain, IpcMainEvent } from 'electron'
import isDev from 'electron-is-dev'
import prepareNext from 'electron-next'
// Prepare the renderer once the app is ready
app.on('ready', async () => {
await prepareNext('./renderer')
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
preload: join(__dirname, 'preload.js')
}
})
const url = isDev
? 'http://localhost:8000/'
: format({
pathname: join(__dirname, '../renderer/index.html'),
protocol: 'file:',
slashes: true
})
mainWindow.loadURL(url)
})
// Quit the app once all windows are closed
app.on('window-all-closed', app.quit)
// listen the channel `message` and resend the received message to the renderer process
ipcMain.on('message', (event: IpcMainEvent, message: any) => {
event.sender.send('message', message)
})
import { ipcRenderer, IpcRenderer } from 'electron'
declare global {
namespace NodeJS {
interface Global {
ipcRenderer: IpcRenderer;
}
}
}
// Since we disabled nodeIntegration we can reintroduce
// needed node functionality here
process.once('loaded', () => {
global.ipcRenderer = ipcRenderer
})
{
"compilerOptions": {
"allowJs": true,
"alwaysStrict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "preserve",
"lib": [
"dom",
"es2017"
],
"module": "commonjs",
"moduleResolution": "node",
"noEmit": false,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"target": "esnext",
"outDir": "../main",
},
"exclude": [
"node_modules"
],
"include": [
"**/*.ts",
"**/*.tsx",
"**/*.js"
]
}
{
"name": "electron-next-skeleton",
"productName": "ElectronTypescriptNext",
"version": "1.0.0",
"main": "main/index.js",
"scripts": {
"start": "electron .",
"build-renderer": "next build renderer && next export renderer",
"build-electron": "tsc -p electron-src",
"build": "yarn build-renderer && yarn build-electron",
"dist": "npm run build && electron-builder --dir",
"type-check": "tsc"
},
"build": {
"asar": false,
"extraResources": [
{
"from": "renderer/out",
"to": "app/renderer"
}
]
},
"devDependencies": {
"@types/next": "8.0.6",
"@types/node": "^11.13.9",
"@types/react": "^16.8.15",
"@types/react-dom": "^16.0.11",
"electron": "^6.0.2",
"electron-builder": "^21.2.0",
"next": "latest",
"typescript": "^3.5.3"
},
"dependencies": {
"electron-is-dev": "^1.0.1",
"electron-next": "^3.1.5",
"react": "^16.7.0",
"react-dom": "^16.7.0"
}
}
import * as React from 'react'
import Link from 'next/link'
import Head from 'next/head'
type Props = {
title?: string
}
const Layout: React.FunctionComponent<Props> = ({
children,
title = 'This is the default title',
}) => (
<div>
<Head>
<title>{title}</title>
<meta charSet="utf-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<header>
<nav>
<Link href="/">
<a>Home</a>
</Link>{' '}
|{' '}
<Link href="/about">
<a>About</a>
</Link>{' '}
|{' '}
<Link href="/initial-props">
<a>With Initial Props</a>
</Link>
</nav>
</header>
{children}
<footer>
<hr />
<span>I'm here to stay (Footer)</span>
</footer>
</div>
)
export default Layout
import * as React from 'react'
import ListItem from './ListItem'
import { User } from '../interfaces'
type Props = {
items: User[]
}
const List: React.FunctionComponent<Props> = ({ items }) => (
<ul>
{items.map(item => (
<li key={item.id}>
<ListItem data={item} />
</li>
))}
</ul>
)
export default List
import * as React from 'react'
import { User } from '../interfaces'
type ListDetailProps = {
item: User
}
const ListDetail: React.FunctionComponent<ListDetailProps> = ({
item: user,
}) => (
<div>
<h1>Detail for {user.name}</h1>
<p>ID: {user.id}</p>
</div>
)
export default ListDetail
import * as React from 'react'
import Link from 'next/link'
import { User } from '../interfaces'
type Props = {
data: User
}
const ListItem: React.FunctionComponent<Props> = ({ data }) => (
<Link href={`/detail?id=${data.id}`}>
<a>
{data.id}: {data.name}
</a>
</Link>
)
export default ListItem
// You can include shared interfaces/types in a separate file
// and then use them in any component by importing them. For
// example, to import the interface below do:
//
// import User from 'path/to/interfaces';
export type User = {
id: number
name: string
}
/// <reference types="next" />
/// <reference types="next/types/global" />
import * as React from 'react'
import Link from 'next/link'
import Layout from '../components/Layout'
const AboutPage: React.FunctionComponent = () => (
<Layout title="About | Next.js + TypeScript + Electron Example">
<h1>About</h1>
<p>This is the about page</p>
<p>
<Link href="/">
<a>Go home</a>
</Link>
</p>
</Layout>
)
export default AboutPage
import * as React from 'react'
import { NextPageContext } from 'next'
import Layout from '../components/Layout'
import { User } from '../interfaces'
import { findData } from '../utils/sample-api'
import ListDetail from '../components/ListDetail'
type Props = {
item?: User
errors?: string
}
class InitialPropsDetail extends React.Component<Props> {
static getInitialProps = async ({ query }: NextPageContext) => {
try {
const { id } = query
const item = await findData(Array.isArray(id) ? id[0] : id)
return { item }
} catch (err) {
return { errors: err.message }
}
}
render() {
const { item, errors } = this.props
if (errors) {
return (
<Layout title={`Error | Next.js + TypeScript + Electron Example`}>
<p>
<span style={{ color: 'red' }}>Error:</span> {errors}
</p>
</Layout>
)
}
return (
<Layout
title={`${item ? item.name : 'Detail'} | Next.js + TypeScript Example`}
>
{item && <ListDetail item={item} />}
</Layout>
)
}
}
export default InitialPropsDetail
import * as React from 'react'
import Link from 'next/link'
import Layout from '../components/Layout'
import { NextPage } from 'next'
const IndexPage: NextPage = () => {
return (
<Layout title="Home | Next.js + TypeScript + Electron Example">
<h1>Hello Next.js 👋</h1>
<p>
<Link href="/about">
<a>About</a>
</Link>
</p>
</Layout>
)
}
export default IndexPage
import { NextPage } from 'next'
import Link from 'next/link'
import Layout from '../components/Layout'
import List from '../components/List'
import { User } from '../interfaces'
import { findAll } from '../utils/sample-api'
type Props = {
items: User[]
pathname: string
}
const WithInitialProps: NextPage<Props> = ({ items, pathname }) => (
<Layout title="List Example (as Functional Component) | Next.js + TypeScript + Electron Example">
<h1>List Example (as Function Component)</h1>
<p>You are currently on: {pathname}</p>
<List items={items} />
<p>
<Link href="/">
<a>Go home</a>
</Link>
</p>
</Layout>
)
WithInitialProps.getInitialProps = async ({ pathname }) => {
// Example for including initial props in a Next.js function compnent page.
// Don't forget to include the respective types for any props passed into
// the component.
const items: User[] = await findAll()
return { items, pathname }
}
export default WithInitialProps
{
"compilerOptions": {
"allowJs": true,
"alwaysStrict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "preserve",
"lib": [
"dom",
"es2017"
],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"target": "esnext"
},
"exclude": [
"node_modules"
],
"include": [
"**/*.ts",
"**/*.tsx",
"**/*.js"
]
}
import { User } from '../interfaces'
/** Dummy user data. */
export const dataArray: User[] = [
{ id: 101, name: 'Alice' },
{ id: 102, name: 'Bob' },
{ id: 103, name: 'Caroline' },
{ id: 104, name: 'Dave' },
]
/**
* Calls a mock API which finds a user by ID from the list above.
*
* Throws an error if not found.
*/
export async function findData(id: number | string) {
const selected = dataArray.find(data => data.id === Number(id))
if (!selected) {
throw new Error('Cannot find user')
}
return selected
}
/** Calls a mock API which returns the above array to simulate "get all". */
export async function findAll() {
// Throw an error, just for example.
if (!Array.isArray(dataArray)) {
throw new Error('Cannot find users')
}
return dataArray
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment