Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to nextjs app router #695

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ coverage

# Editor
.vscode
.idea

# System
.DS_Store
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## Unreleased

## [0.21.7](https://github.com/o1-labs/zkapp-cli/compare/0.21.6...0.21.7) - 2024-09-19

### Changed

- Updated Next.js project starter to use app router and skip `src` directory

## [0.21.6](https://github.com/o1-labs/zkapp-cli/compare/0.21.5...0.21.6) - 2024-09-03

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zkapp-cli",
"version": "0.21.6",
"version": "0.21.7",
"description": "CLI to create zkApps (zero-knowledge apps) for Mina Protocol",
"homepage": "https://github.com/o1-labs/zkapp-cli/",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion src/bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ yargs(hideBin(process.argv))
// chalk.reset is a hack to force the terminal to retain a line break below
chalk.reset(
`

__ _
/_ | | |
___ | | __ _| |__ ___
Expand Down
116 changes: 45 additions & 71 deletions src/lib/project.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import util from 'node:util';
import ora from 'ora';
import shell from 'shelljs';
import customNextIndex from '../lib/ui/next/customNextIndex.js';
import customNextPage from '../lib/ui/next/customNextPage.js';
import customNextLayout from '../lib/ui/next/customNextLayout.js';
import customNuxtIndex from '../lib/ui/nuxt/customNuxtIndex.js';
import nuxtGradientBackground from '../lib/ui/nuxt/nuxtGradientBackground.js';
import customLayoutSvelte from '../lib/ui/svelte/customLayoutSvelte.js';
Expand Down Expand Up @@ -314,12 +315,13 @@
// set the project name and default flags
// https://nextjs.org/docs/api-reference/create-next-app#options
let args = [
'[email protected].3',
'[email protected].12',
'ui',
'--use-npm',
'--src-dir',
'--no-src-dir',
'--ts',
'--import-alias "@/*"',
'--no-app',
'--app',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add this change to the changelog?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

];

spawnSync('npx', args, {
Expand All @@ -328,19 +330,8 @@
});

shell.rm('-rf', path.join('ui', '.git')); // Remove NextJS' .git; we will init .git in our monorepo's root.
// Read in the NextJS config file and add the middleware.

let useTypescript = true;
try {
// Determine if generated project is a ts project by looking for a tsconfig file
fs.readFileSync(path.join('ui', 'tsconfig.json'));
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err);
}
useTypescript = false;
}

// Read in the NextJS config file and add the middleware.
const nextConfig = fs.readFileSync(
path.join('ui', 'next.config.mjs'),
'utf8'
Expand All @@ -354,8 +345,9 @@

`;
newNextConfig += nextConfig.replace(
/^};(.*?)$/gm, // Search for the last '};' in the file.
'};',
`
reactStrictMode: false,
webpack(config, { isServer }) {
if (!isServer) {
config.resolve.alias = {
Expand Down Expand Up @@ -390,36 +382,41 @@
};`
);

// This prevents usEffect from running twice on initial mount.
newNextConfig = newNextConfig.replace(
'reactStrictMode: true',
'reactStrictMode: false'
);

fs.writeFileSync(path.join('ui', 'next.config.mjs'), newNextConfig);

const indexFileName = useTypescript ? 'index.tsx' : 'index.js';
const pageFileName = 'page.tsx';

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like there are some legacy create-next-app boilerplate styles and fonts leftover in the app folder when a project is generated. I think it is a good idea to remove these so they do not conflict with the other assets. You could empty the app directory with something like fs.emptyDirSync or similar before adding the customNextPage and any other files to the directory.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, cleared out the whole directory

fs.writeFileSync(
path.join('ui', 'app', pageFileName),
customNextPage,
'utf8'
);

const layoutFileName = 'layout.tsx';

fs.writeFileSync(
path.join('ui', 'src/pages', indexFileName),
customNextIndex,
path.join('ui', 'app', layoutFileName),
customNextLayout,
'utf8'
);

// Adds landing page components directory and files to NextJS project.
fs.copySync(
path.join(__dirname, 'ui', 'next', 'components'),
path.join('ui', 'src', 'components')
path.join('ui', 'components')
);

// Adds landing page style directory and files to NextJS project.
fs.copySync(
path.join(__dirname, 'ui', 'next', 'styles'),
path.join('ui', 'src', 'styles')
path.join('ui', 'styles')
);

// Removes create-next-app assets
fs.emptyDirSync(path.join('ui', 'public'));
if (fs.existsSync(path.join('ui', 'app', 'favicon.ico'))) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar comment to above.
It looks like there are some legacy create-next-app boilerplate styles and fonts leftover in the app folder when a project is generated. You could empty the entire app directory instead of just removing the favicon here with something like fs.emptyDirSync or similar before adding the customNextPage and any other files to the directory.

shell.rm('-rf', path.join('ui', 'app', 'favicon.ico'));

Check warning on line 418 in src/lib/project.js

View check run for this annotation

Codecov / codecov/patch

src/lib/project.js#L418

Added line #L418 was not covered by tests
}

// Adds landing page assets directory and files to NextJS project.
fs.copySync(
Expand Down Expand Up @@ -452,23 +449,26 @@
"jsx": "preserve",
"paths": {
"@/*": ["./src/*"]
}
},
"plugins": [
{
"name": "next"
}
]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
`;

if (useTypescript) {
fs.writeFileSync(path.join('ui', 'tsconfig.json'), tsconfig);
fs.writeFileSync(path.join('ui', 'tsconfig.json'), tsconfig);

// Add a script to the package.json
let x = fs.readJsonSync(path.join('ui', 'package.json'));
x.scripts['ts-watch'] = 'tsc --noEmit --incremental --watch';
x.scripts['build'] = 'next build --no-lint';
x.type = 'module';
fs.writeJSONSync(path.join('ui', 'package.json'), x, { spaces: 2 });
}
// Add a script to the package.json
let x = fs.readJsonSync(path.join('ui', 'package.json'));
x.scripts['ts-watch'] = 'tsc --noEmit --incremental --watch';
x.scripts['build'] = 'next build --no-lint';
x.type = 'module';
fs.writeJSONSync(path.join('ui', 'package.json'), x, { spaces: 2 });

if (useGHPages) {
const isWindows = process.platform === 'win32';
Expand Down Expand Up @@ -510,13 +510,6 @@
return config;`
);

// update page extensions
newNextConfig = newNextConfig.replace(
'reactStrictMode: false,',
`reactStrictMode: false,
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],`
);

fs.writeFileSync(path.join('ui', 'next.config.mjs'), newNextConfig);

// Add some scripts to the package.json
Expand Down Expand Up @@ -548,42 +541,23 @@
);
shell.cd('..');

const appFileName = useTypescript ? '_app.tsx' : '_app.js';
const appPagesFileName = useTypescript ? '_app.page.tsx' : '_app.page.js';
const indexFileName = useTypescript ? 'index.tsx' : 'index.js';
const indexPagesFileName = useTypescript
? 'index.page.tsx'
: 'index.page.js';
const reactCOIServiceWorkerFileName = useTypescript
? 'reactCOIServiceWorker.tsx'
: 'reactCOIServiceWorker.js';
shell.mv(
path.join('ui', 'src/pages', appFileName),
path.join('ui', 'src/pages', appPagesFileName)
);
shell.mv(
path.join('ui', 'src/pages', indexFileName),
path.join('ui', 'src/pages', indexPagesFileName)
);
const reactCOIServiceWorkerFileName = 'reactCOIServiceWorker.tsx';

let appFile = fs.readFileSync(
path.join('ui', 'src', 'pages', appPagesFileName),
let pageFile = fs.readFileSync(
path.join('ui', 'app', pageFileName),
'utf8'
);

appFile = appFile.replace(
pageFile = pageFile.replace(
'export default function',
`import './reactCOIServiceWorker';

export default function`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@essential-breads were you able to test if the deploy to GitHub Pages flow works correctly with the appRouter changes? It might be out of scope for this PR, but I will add an issue so we don't forget to verify that everything works.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep GH pages is fully tested!

);
fs.writeFileSync(
path.join('ui', 'src', 'pages', appPagesFileName),
appFile
);
fs.writeFileSync(path.join('ui', 'app', pageFileName), pageFile);

fs.writeFileSync(
path.join('ui', 'src', 'pages', reactCOIServiceWorkerFileName),
path.join('ui', 'app', reactCOIServiceWorkerFileName),
`export {};

function loadCOIServiceWorker() {
Expand Down
14 changes: 8 additions & 6 deletions src/lib/project.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,12 +205,13 @@ describe('project.js', () => {
expect(spawnSync).toHaveBeenCalledWith(
'npx',
[
'[email protected].3',
'[email protected].12',
'ui',
'--use-npm',
'--src-dir',
'--no-src-dir',
'--ts',
'--import-alias "@/*"',
'--no-app',
'--app',
],
{
stdio: 'inherit',
Expand Down Expand Up @@ -621,12 +622,13 @@ describe('project.js', () => {
expect(spawnSync).toHaveBeenCalledWith(
'npx',
[
'[email protected].3',
'[email protected].12',
'ui',
'--use-npm',
'--src-dir',
'--no-src-dir',
'--ts',
'--import-alias "@/*"',
'--no-app',
'--app',
],
{
stdio: 'inherit',
Expand Down
2 changes: 1 addition & 1 deletion src/lib/ui/next/components/GradientBG.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-nocheck
import styles from '@/styles/Home.module.css';
import styles from '../styles/Home.module.css';
import { useEffect, useState, useRef } from 'react';

export default function GradientBG({ children }) {
Expand Down
18 changes: 18 additions & 0 deletions src/lib/ui/next/customNextLayout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export default `import "../styles/globals.css";

export const metadata = {
title: 'Mina zkApp UI',
description: 'built with o1js',
icons: {
icon: '/assets/favicon.ico',
},
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
`;
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
export default `
export default `'use client';
import Head from 'next/head';
import Image from 'next/image';
import { useEffect } from 'react';
import GradientBG from '../components/GradientBG.js';
import styles from '../styles/Home.module.css';
import heroMinaLogo from '../../public/assets/hero-mina-logo.svg';
import arrowRightSmall from '../../public/assets/arrow-right-small.svg';
import heroMinaLogo from '../public/assets/hero-mina-logo.svg';
import arrowRightSmall from '../public/assets/arrow-right-small.svg';

export default function Home() {
useEffect(() => {
(async () => {
const { Mina, PublicKey } = await import('o1js');
const { Add } = await import('../../../contracts/build/src/');
const { Add } = await import('../../contracts/build/src/');

// Update this to use the address (public key) for your zkApp account.
// To try it out, you can try this address for an example "Add" smart contract that we've deployed to
Expand Down
12 changes: 6 additions & 6 deletions src/lib/ui/next/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@
font-family: 'ABC Monument Grotesk';
font-style: normal;
font-weight: normal;
src: url('/assets/fonts/ABCMonumentGrotesk-Regular.woff2') format('woff2'),
url('/assets/fonts/ABCMonumentGrotesk-Regular.woff') format('woff');
src: url('../public/assets/fonts/ABCMonumentGrotesk-Regular.woff2') format('woff2'),
url('../public/assets/fonts/ABCMonumentGrotesk-Regular.woff') format('woff');
}

@font-face {
font-family: 'ABC Monument Grotesk Light';
font-style: normal;
src: url('/assets/fonts/ABCMonumentGrotesk-Light.woff2') format('woff2'),
url('/assets/fonts/ABCMonumentGrotesk-Light.woff') format('woff');
src: url('../public/assets/fonts/ABCMonumentGrotesk-Light.woff2') format('woff2'),
url('../public/assets/fonts/ABCMonumentGrotesk-Light.woff') format('woff');
}

@font-face {
font-family: 'ABC Monument Grotesk Bold';
font-style: normal;
font-weight: bold;
src: url('/assets/fonts/ABCMonumentGrotesk-Bold.woff2') format('woff2'),
url('/assets/fonts/ABCMonumentGrotesk-Bold.woff') format('woff');
src: url('../public/assets/fonts/ABCMonumentGrotesk-Bold.woff2') format('woff2'),
url('../public/assets/fonts/ABCMonumentGrotesk-Bold.woff') format('woff');
}

:root {
Expand Down