Module

x/fresh/init.ts

The next-gen web framework.
Extremely Popular
Go to Latest
File
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
import { basename, colors, join, parse, resolve } from "./src/dev/deps.ts";import { error } from "./src/dev/error.ts";import { collect, ensureMinDenoVersion, generate } from "./src/dev/mod.ts";import { dotenvImports, freshImports, twindImports,} from "./src/dev/imports.ts";
ensureMinDenoVersion();
const help = `fresh-init
Initialize a new Fresh project. This will create all the necessary files for anew project.
To generate a project in the './foobar' subdirectory: fresh-init ./foobar
To generate a project in the current directory: fresh-init .
USAGE: fresh-init [DIRECTORY]
OPTIONS: --force Overwrite existing files --twind Setup project to use 'twind' for styling --vscode Setup project for VSCode --docker Setup Project to use Docker`;
const CONFIRM_EMPTY_MESSAGE = "The target directory is not empty (files could get overwritten). Do you want to continue anyway?";
const USE_TWIND_MESSAGE = "Fresh has built in support for styling using Tailwind CSS. Do you want to use this?";
const USE_VSCODE_MESSAGE = "Do you use VS Code?";
const flags = parse(Deno.args, { boolean: ["force", "twind", "vscode", "docker"], default: { "force": null, "twind": null, "vscode": null, "docker": null },});
console.log();console.log( colors.bgRgb8( colors.black(colors.bold(" 🍋 Fresh: The next-gen web framework. ")), 121, ),);console.log();
let unresolvedDirectory = Deno.args[0];if (flags._.length !== 1) { const userInput = prompt("Project Name", "fresh-project"); if (!userInput) { error(help); }
unresolvedDirectory = userInput;}
const resolvedDirectory = resolve(unresolvedDirectory);
try { const dir = [...Deno.readDirSync(resolvedDirectory)]; const isEmpty = dir.length === 0 || dir.length === 1 && dir[0].name === ".git"; if ( !isEmpty && !(flags.force === null ? confirm(CONFIRM_EMPTY_MESSAGE) : flags.force) ) { error("Directory is not empty."); }} catch (err) { if (!(err instanceof Deno.errors.NotFound)) { throw err; }}console.log("%cLet's set up your new Fresh project.\n", "font-weight: bold");
const useTwind = flags.twind === null ? confirm(USE_TWIND_MESSAGE) : flags.twind;
const useVSCode = flags.vscode === null ? confirm(USE_VSCODE_MESSAGE) : flags.vscode;
const useDocker = flags.docker;
await Deno.mkdir(join(resolvedDirectory, "routes", "api"), { recursive: true });await Deno.mkdir(join(resolvedDirectory, "islands"), { recursive: true });await Deno.mkdir(join(resolvedDirectory, "static"), { recursive: true });await Deno.mkdir(join(resolvedDirectory, "components"), { recursive: true });if (useVSCode) { await Deno.mkdir(join(resolvedDirectory, ".vscode"), { recursive: true });}
const GITIGNORE = `# dotenv environment variable files.env.env.development.local.env.test.local.env.production.local.env.local
# Fresh build directory_fresh/`;
await Deno.writeTextFile( join(resolvedDirectory, ".gitignore"), GITIGNORE,);
if (useDocker) { const DENO_VERSION = Deno.version.deno; const DOCKERFILE_TEXT = `FROM denoland/deno:${DENO_VERSION}
ARG GIT_REVISIONENV DENO_DEPLOYMENT_ID=\${GIT_REVISION}
WORKDIR /app
COPY . .RUN deno cache main.ts
EXPOSE 8000
CMD ["run", "-A", "main.ts"]
`;
await Deno.writeTextFile( join(resolvedDirectory, "Dockerfile"), DOCKERFILE_TEXT, );}
const ROUTES_INDEX_TSX = `import { useSignal } from "@preact/signals";import Counter from "../islands/Counter.tsx";
export default function Home() { const count = useSignal(3); return ( <div class="px-4 py-8 mx-auto bg-[#86efac]"> <div class="max-w-screen-md mx-auto flex flex-col items-center justify-center"> <img class="my-6" src="/logo.svg" width="128" height="128" alt="the Fresh logo: a sliced lemon dripping with juice" /> <h1 class="text-4xl font-bold">Welcome to Fresh</h1> <p class="my-4"> Try updating this message in the <code class="mx-2">./routes/index.tsx</code> file, and refresh. </p> <Counter count={count} /> </div> </div> );}`;await Deno.writeTextFile( join(resolvedDirectory, "routes", "index.tsx"), ROUTES_INDEX_TSX,);
const COMPONENTS_BUTTON_TSX = `import { JSX } from "preact";import { IS_BROWSER } from "$fresh/runtime.ts";
export function Button(props: JSX.HTMLAttributes<HTMLButtonElement>) { return ( <button {...props} disabled={!IS_BROWSER || props.disabled} class="px-2 py-1 border-gray-500 border-2 rounded bg-white hover:bg-gray-200 transition-colors" /> );}`;await Deno.writeTextFile( join(resolvedDirectory, "components", "Button.tsx"), COMPONENTS_BUTTON_TSX,);
const ISLANDS_COUNTER_TSX = `import type { Signal } from "@preact/signals";import { Button } from "../components/Button.tsx";
interface CounterProps { count: Signal<number>;}
export default function Counter(props: CounterProps) { return ( <div class="flex gap-8 py-6"> <Button onClick={() => props.count.value -= 1}>-1</Button> <p class="text-3xl">{props.count}</p> <Button onClick={() => props.count.value += 1}>+1</Button> </div> );}`;await Deno.writeTextFile( join(resolvedDirectory, "islands", "Counter.tsx"), ISLANDS_COUNTER_TSX,);
const ROUTES_GREET_TSX = `import { PageProps } from "$fresh/server.ts";
export default function Greet(props: PageProps) { return <div>Hello {props.params.name}</div>;}`;await Deno.mkdir(join(resolvedDirectory, "routes", "greet"), { recursive: true,});await Deno.writeTextFile( join(resolvedDirectory, "routes", "greet", "[name].tsx"), ROUTES_GREET_TSX,);
// 404 pageconst ROUTES_404_PAGE = `import { Head } from "$fresh/runtime.ts";
export default function Error404() { return ( <> <Head> <title>404 - Page not found</title> </Head> <div class="px-4 py-8 mx-auto bg-[#86efac]"> <div class="max-w-screen-md mx-auto flex flex-col items-center justify-center"> <img class="my-6" src="/logo.svg" width="128" height="128" alt="the Fresh logo: a sliced lemon dripping with juice" /> <h1 class="text-4xl font-bold">404 - Page not found</h1> <p class="my-4"> The page you were looking for doesn't exist. </p> <a href="/" class="underline">Go back home</a> </div> </div> </> );}`;
await Deno.writeTextFile( join(resolvedDirectory, "routes", "_404.tsx"), ROUTES_404_PAGE,);
const ROUTES_API_JOKE_TS = `import { HandlerContext } from "$fresh/server.ts";
// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/const JOKES = [ "Why do Java developers often wear glasses? They can't C#.", "A SQL query walks into a bar, goes up to two tables and says “can I join you?”", "Wasn't hard to crack Forrest Gump's password. 1forrest1.", "I love pressing the F5 key. It's refreshing.", "Called IT support and a chap from Australia came to fix my network connection. I asked “Do you come from a LAN down under?”", "There are 10 types of people in the world. Those who understand binary and those who don't.", "Why are assembly programmers often wet? They work below C level.", "My favourite computer based band is the Black IPs.", "What programme do you use to predict the music tastes of former US presidential candidates? An Al Gore Rhythm.", "An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.",];
export const handler = (_req: Request, _ctx: HandlerContext): Response => { const randomIndex = Math.floor(Math.random() * JOKES.length); const body = JOKES[randomIndex]; return new Response(body);};`;await Deno.writeTextFile( join(resolvedDirectory, "routes", "api", "joke.ts"), ROUTES_API_JOKE_TS,);
const TWIND_CONFIG_TS = `import { Options } from "$fresh/plugins/twind.ts";
export default { selfURL: import.meta.url,} as Options;`;if (useTwind) { await Deno.writeTextFile( join(resolvedDirectory, "twind.config.ts"), TWIND_CONFIG_TS, );}
const NO_TWIND_STYLES = `*,*::before,*::after { box-sizing: border-box;}* { margin: 0;}button { color: inherit;}button, [role="button"] { cursor: pointer;}code { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 1em;}img,svg { display: block;}img,video { max-width: 100%; height: auto;}
html { line-height: 1.5; -webkit-text-size-adjust: 100%; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";}.transition-colors { transition-property: background-color, border-color, color, fill, stroke; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms;}.my-6 { margin-bottom: 1.5rem; margin-top: 1.5rem;}.text-4xl { font-size: 2.25rem; line-height: 2.5rem;}.mx-2 { margin-left: 0.5rem; margin-right: 0.5rem;}.my-4 { margin-bottom: 1rem; margin-top: 1rem;}.mx-auto { margin-left: auto; margin-right: auto;}.px-4 { padding-left: 1rem; padding-right: 1rem;}.py-8 { padding-bottom: 2rem; padding-top: 2rem;}.bg-\\[\\#86efac\\] { background-color: #86efac;}.text-3xl { font-size: 1.875rem; line-height: 2.25rem;}.py-6 { padding-bottom: 1.5rem; padding-top: 1.5rem;}.px-2 { padding-left: 0.5rem; padding-right: 0.5rem;}.py-1 { padding-bottom: 0.25rem; padding-top: 0.25rem;}.border-gray-500 { border-color: #6b7280;}.bg-white { background-color: #fff;}.flex { display: flex;}.gap-8 { grid-gap: 2rem; gap: 2rem;}.font-bold { font-weight: 700;}.max-w-screen-md { max-width: 768px;}.flex-col { flex-direction: column;}.items-center { align-items: center;}.justify-center { justify-content: center;}.border-2 { border-width: 2px;}.rounded { border-radius: 0.25rem;}.hover\:bg-gray-200:hover { background-color: #e5e7eb;}`;
const APP_WRAPPER = useTwind ? `import { AppProps } from "$fresh/server.ts";
export default function App({ Component }: AppProps) { return ( <html> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>${basename(resolvedDirectory)}</title> </head> <body> <Component /> </body> </html> );}` : `import { AppProps } from "$fresh/server.ts";
export default function App({ Component }: AppProps) { return ( <html> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>${basename(resolvedDirectory)}</title> <link rel="stylesheet" href="/styles.css" /> </head> <body> <Component /> </body> </html> );}`;
if (!useTwind) { await Deno.writeTextFile( join(resolvedDirectory, "static", "styles.css"), NO_TWIND_STYLES, );}
await Deno.writeTextFile( join(resolvedDirectory, "routes", "_app.tsx"), APP_WRAPPER,);
const STATIC_LOGO = `<svg width="40" height="40" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M34.092 8.845C38.929 20.652 34.092 27 30 30.5c1 3.5-2.986 4.222-4.5 2.5-4.457 1.537-13.512 1.487-20-5C2 24.5 4.73 16.714 14 11.5c8-4.5 16-7 20.092-2.655Z" fill="#FFDB1E"/> <path d="M14 11.5c6.848-4.497 15.025-6.38 18.368-3.47C37.5 12.5 21.5 22.612 15.5 25c-6.5 2.587-3 8.5-6.5 8.5-3 0-2.5-4-5.183-7.75C2.232 23.535 6.16 16.648 14 11.5Z" fill="#fff" stroke="#FFDB1E"/> <path d="M28.535 8.772c4.645 1.25-.365 5.695-4.303 8.536-3.732 2.692-6.606 4.21-7.923 4.83-.366.173-1.617-2.252-1.617-1 0 .417-.7 2.238-.934 2.326-1.365.512-4.223 1.29-5.835 1.29-3.491 0-1.923-4.754 3.014-9.122.892-.789 1.478-.645 2.283-.645-.537-.773-.534-.917.403-1.546C17.79 10.64 23 8.77 25.212 8.42c.366.014.82.35.82.629.41-.14 2.095-.388 2.503-.278Z" fill="#FFE600"/> <path d="M14.297 16.49c.985-.747 1.644-1.01 2.099-2.526.566.121.841-.08 1.29-.701.324.466 1.657.608 2.453.701-.715.451-1.057.852-1.452 2.106-1.464-.611-3.167-.302-4.39.42Z" fill="#fff"/></svg>`;
await Deno.writeTextFile( join(resolvedDirectory, "static", "logo.svg"), STATIC_LOGO,);
try { const faviconArrayBuffer = await fetch("https://fresh.deno.dev/favicon.ico") .then((d) => d.arrayBuffer()); await Deno.writeFile( join(resolvedDirectory, "static", "favicon.ico"), new Uint8Array(faviconArrayBuffer), );} catch { // Skip this and be silent if there is a network issue.}
let FRESH_CONFIG_TS = `import { defineConfig } from "$fresh/server.ts";\n`;if (useTwind) { FRESH_CONFIG_TS += `import twindPlugin from "$fresh/plugins/twind.ts"import twindConfig from "./twind.config.ts";`;}
FRESH_CONFIG_TS += `export default defineConfig({${ useTwind ? `\n plugins: [twindPlugin(twindConfig)]\n` : ""}});`;const CONFIG_TS_PATH = join(resolvedDirectory, "fresh.config.ts");await Deno.writeTextFile(CONFIG_TS_PATH, FRESH_CONFIG_TS);
let MAIN_TS = `/// <reference no-default-lib="true" />/// <reference lib="dom" />/// <reference lib="dom.iterable" />/// <reference lib="dom.asynciterable" />/// <reference lib="deno.ns" />
import "$std/dotenv/load.ts";
import { start } from "$fresh/server.ts";import manifest from "./fresh.gen.ts";import config from "./fresh.config.ts";`;
MAIN_TS += `await start(manifest, config);\n`;const MAIN_TS_PATH = join(resolvedDirectory, "main.ts");await Deno.writeTextFile(MAIN_TS_PATH, MAIN_TS);
const DEV_TS = `#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";import config from "./fresh.config.ts";
await dev(import.meta.url, "./main.ts", config);`;const DEV_TS_PATH = join(resolvedDirectory, "dev.ts");await Deno.writeTextFile(DEV_TS_PATH, DEV_TS);try { await Deno.chmod(DEV_TS_PATH, 0o777);} catch { // this throws on windows}
const config = { lock: false, tasks: { check: "deno fmt --check && deno lint && deno check **/*.ts && deno check **/*.tsx", start: "deno run -A --watch=static/,routes/ dev.ts", build: "deno run -A dev.ts build", preview: "deno run -A main.ts", update: "deno run -A -r https://fresh.deno.dev/update .", }, lint: { rules: { tags: ["fresh", "recommended"], }, }, imports: {} as Record<string, string>, compilerOptions: { jsx: "react-jsx", jsxImportSource: "preact", },};freshImports(config.imports);if (useTwind) twindImports(config.imports);dotenvImports(config.imports);
const DENO_CONFIG = JSON.stringify(config, null, 2) + "\n";
await Deno.writeTextFile(join(resolvedDirectory, "deno.json"), DENO_CONFIG);
const README_MD = `# Fresh project
Your new Fresh project is ready to go. You can follow the Fresh "GettingStarted" guide here: https://fresh.deno.dev/docs/getting-started
### Usage
Make sure to install Deno: https://deno.land/manual/getting_started/installation
Then start the project:
\`\`\`deno task start\`\`\`
This will watch the project directory and restart as necessary.`;await Deno.writeTextFile( join(resolvedDirectory, "README.md"), README_MD,);
const vscodeSettings = { "deno.enable": true, "deno.lint": true, "editor.defaultFormatter": "denoland.vscode-deno", "[typescriptreact]": { "editor.defaultFormatter": "denoland.vscode-deno", }, "[typescript]": { "editor.defaultFormatter": "denoland.vscode-deno", }, "[javascriptreact]": { "editor.defaultFormatter": "denoland.vscode-deno", }, "[javascript]": { "editor.defaultFormatter": "denoland.vscode-deno", },};
const VSCODE_SETTINGS = JSON.stringify(vscodeSettings, null, 2) + "\n";
if (useVSCode) { await Deno.writeTextFile( join(resolvedDirectory, ".vscode", "settings.json"), VSCODE_SETTINGS, );}
const vscodeExtensions = { recommendations: ["denoland.vscode-deno"],};
if (useTwind) { vscodeExtensions.recommendations.push("sastan.twind-intellisense");}
const VSCODE_EXTENSIONS = JSON.stringify(vscodeExtensions, null, 2) + "\n";
if (useVSCode) { await Deno.writeTextFile( join(resolvedDirectory, ".vscode", "extensions.json"), VSCODE_EXTENSIONS, );}
const manifest = await collect(resolvedDirectory);await generate(resolvedDirectory, manifest);
// Specifically print unresolvedDirectory, rather than resolvedDirectory in order to// not leak personal info (e.g. `/Users/MyName`)console.log("\n%cProject initialized!\n", "color: green; font-weight: bold");
if (unresolvedDirectory !== ".") { console.log( `Enter your project directory using %ccd ${unresolvedDirectory}%c.`, "color: cyan", "", );}console.log( "Run %cdeno task start%c to start the project. %cCTRL-C%c to stop.", "color: cyan", "", "color: cyan", "",);console.log();console.log( "Stuck? Join our Discord %chttps://discord.gg/deno", "color: cyan", "",);console.log();console.log( "%cHappy hacking! 🦕", "color: gray",);