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

feat(create-astro): add peer dependencies to package.json #2843

Merged
merged 8 commits into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 5 additions & 0 deletions .changeset/rude-starfishes-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'create-astro': minor
---

Install dependencies automatically
3 changes: 3 additions & 0 deletions packages/create-astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,13 @@
"degit": "^2.8.4",
"kleur": "^4.1.4",
"node-fetch": "^3.2.3",
"ora": "^6.1.0",
"prompts": "^2.4.2",
"which-pm-runs": "^1.1.0",
"yargs-parser": "^21.0.1"
},
"devDependencies": {
"@types/which-pm-runs": "^1.0.0",
"@types/yargs-parser": "^21.0.0",
"astro-scripts": "workspace:*",
"uvu": "^0.5.3"
Expand Down
8 changes: 5 additions & 3 deletions packages/create-astro/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
export const createConfig = ({ integrations }: { integrations: string[] }) => {
import type { Integration } from './frameworks';

export const createConfig = ({ integrations }: { integrations: Integration[] }) => {
if (integrations.length === 0) {
return `import { defineConfig } from 'astro/config';
// https://astro.build/config
export default defineConfig({});
`;
}

const rendererImports = integrations.map((r: string) => ` import ${r} from '@astrojs/${r === 'solid' ? 'solid-js' : r}';`);
const rendererIntegrations = integrations.map((r: string) => ` ${r}(),`);
const rendererImports = integrations.map((r) => ` import ${r.id} from '${r.packageName}';`);
const rendererIntegrations = integrations.map((r) => ` ${r.id}(),`);
return [
`import { defineConfig } from 'astro/config';`,
...rendererImports,
Expand Down
27 changes: 16 additions & 11 deletions packages/create-astro/src/frameworks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,25 +107,30 @@ export default {
},
};

export const FRAMEWORKS = [
export interface Integration {
id: string;
packageName: string;
}

export const FRAMEWORKS: { title: string; value: Integration }[] = [
{
title: 'preact',
value: '@astrojs/preact',
title: 'Preact',
value: { id: 'preact', packageName: '@astrojs/preact' },
},
{
title: 'react',
value: 'react',
title: 'React',
value: { id: 'react', packageName: '@astrojs/react' },
},
{
title: 'solid',
value: 'solid',
title: 'Solid.js',
value: { id: 'solid', packageName: '@astrojs/solid-js' },
},
{
title: 'svelte',
value: 'svelte',
title: 'Svelte',
value: { id: 'svelte', packageName: '@astrojs/svelte' },
},
{
title: 'vue',
value: 'vue',
title: 'Vue',
value: { id: 'vue', packageName: '@astrojs/vue' },
},
];
103 changes: 85 additions & 18 deletions packages/create-astro/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import fs from 'fs';
import path from 'path';
import { exec as childProcessExec, ExecOptions } from 'child_process';
import { bold, cyan, gray, green, red, yellow } from 'kleur/colors';
import fetch from 'node-fetch';
import prompts from 'prompts';
import degit from 'degit';
import yargs from 'yargs-parser';
import { FRAMEWORKS, COUNTER_COMPONENTS } from './frameworks.js';
import ora from 'ora';
import whichPM from 'which-pm-runs';
import { FRAMEWORKS, COUNTER_COMPONENTS, Integration } from './frameworks.js';
import { TEMPLATES } from './templates.js';
import { createConfig } from './config.js';
import { logger, defaultLogLevel } from './logger.js';
Expand All @@ -27,17 +30,32 @@ export function mkdirp(dir: string) {
}
}

function exec(command: string[], options: ExecOptions = {}) {
return new Promise((resolve, reject) => {
childProcessExec(command.join(' '), options, (err, stdout, stderr) => {
if (err) {
reject(stderr);
} else {
resolve(stdout);
}
});
});
}

const { version } = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));

const POSTPROCESS_FILES = ['package.json', 'astro.config.mjs', 'CHANGELOG.md']; // some files need processing after copying.

const issueMsg = '\nIf you think this is an error, feel free to open an issue in our GitHub repo: https://github.com/withastro/astro/issues/new';

export async function main() {
logger.debug('Verbose logging turned on');
console.log(`\n${bold('Welcome to Astro!')} ${gray(`(create-astro v${version})`)}`);
console.log(`If you encounter a problem, visit ${cyan('https://github.com/withastro/astro/issues')} to search or file a new issue.\n`);

console.log(`${green(`>`)} ${gray(`Prepare for liftoff.`)}`);
console.log(`${green(`>`)} ${gray(`Gathering mission details...`)}`);
let spinner = ora({ color: 'green', text: 'Prepare for liftoff.' });

spinner.succeed();

const cwd = (args['_'][2] as string) || '.';
if (fs.existsSync(cwd)) {
Expand All @@ -57,7 +75,7 @@ export async function main() {
mkdirp(cwd);
}

const options = /** @type {import('./types/internal').Options} */ await prompts([
const options = await prompts([
{
type: 'select',
name: 'template',
Expand Down Expand Up @@ -87,10 +105,10 @@ export async function main() {
});

const selectedTemplate = TEMPLATES.find((template) => template.value === options.template);
let integrations: string[] = [];
let integrations: Integration[] = [];

if (selectedTemplate?.integrations === true) {
const result = /** @type {import('./types/internal').Options} */ await prompts([
const result = await prompts([
{
type: 'multiselect',
name: 'integrations',
Expand All @@ -101,12 +119,13 @@ export async function main() {
integrations = result.integrations;
}

spinner = ora({ color: 'green', text: 'Copying project files...' }).start();

// Copy
try {
emitter.on('info', (info) => {
logger.debug(info.message);
});
console.log(`${green(`>`)} ${gray(`Copying project files...`)}`);
await emitter.clone(cwd);
} catch (err: any) {
// degit is compiled, so the stacktrace is pretty noisy. Only report the stacktrace when using verbose mode.
Expand All @@ -128,6 +147,7 @@ export async function main() {
)
);
}
spinner.fail();
process.exit(1);
}

Expand All @@ -154,13 +174,25 @@ export async function main() {
const packageJSON = JSON.parse(await fs.promises.readFile(fileLoc, 'utf8'));
delete packageJSON.snowpack; // delete snowpack config only needed in monorepo (can mess up projects)
// Fetch latest versions of selected integrations
const integrationEntries = (await Promise.all(
['astro', ...integrations].map((integration: string) =>
fetch(`https://registry.npmjs.org/@astrojs/${integration === 'solid' ? 'solid-js' : integration}/latest`)
.then((res: any) => res.json())
.then((res: any) => [res['name'], `^${res['version']}`])
const integrationEntries = (
await Promise.all(
integrations.map((integration) =>
fetch(`https://registry.npmjs.org/${integration.packageName}/latest`)
.then((res) => res.json())
.then((res: any) => {
let dependencies = [[res['name'], `^${res['version']}`]];

if (res['peerDependencies']) {
for (const peer in res['peerDependencies']) {
dependencies.push([peer, res['peerDependencies'][peer]]);
}
}

return dependencies;
})
)
)
)) as any;
).flat(1);
packageJSON.devDependencies = { ...(packageJSON.devDependencies ?? {}), ...Object.fromEntries(integrationEntries) };
await fs.promises.writeFile(fileLoc, JSON.stringify(packageJSON, undefined, 2));
break;
Expand All @@ -174,8 +206,8 @@ export async function main() {
let importStatements: string[] = [];
let components: string[] = [];
await Promise.all(
integrations.map(async (integrations) => {
const component = COUNTER_COMPONENTS[integrations as keyof typeof COUNTER_COMPONENTS];
integrations.map(async (integration) => {
const component = COUNTER_COMPONENTS[integration.id as keyof typeof COUNTER_COMPONENTS];
const componentName = path.basename(component.filename, path.extname(component.filename));
const absFileLoc = path.resolve(cwd, component.filename);
importStatements.push(`import ${componentName} from '${component.filename.replace(/^src/, '..')}';`);
Expand All @@ -196,6 +228,36 @@ export async function main() {
await fs.promises.writeFile(pageFileLoc, newContent);
}

spinner.succeed();

const { name: pm } = whichPM() || { name: 'not_found' };
const supportedPM = ['npm', 'yarn', 'pnpm'].includes(pm);

if (supportedPM) {
spinner = ora({ color: 'green', text: 'Installing dependencies...' }).start();
natemoo-re marked this conversation as resolved.
Show resolved Hide resolved
try {
if (pm === 'yarn') await exec(['yarn'], { cwd });
else if (pm === 'pnpm') await exec(['pnpm', 'install'], { cwd });
else await exec(['npm', 'install'], { cwd });

spinner.succeed();
} catch (error) {
spinner.fail('There was an error installing the dependencies.\n' + `You can try to run ${bold(cyan(`${pm} install`))} manually.` + issueMsg);
console.error(error);
}
}

try {
spinner = ora({ color: 'green', text: 'Initializating git...' }).start();
await exec(['git', 'init'], { cwd });
await exec(['git', 'add', '-A'], { cwd });
await exec(['git', 'commit', '-m', '"Initial commit"'], { cwd });
spinner.succeed();
} catch (error) {
spinner.fail();
logger.debug('Error with git init', error);
}

console.log(bold(green('✔') + ' Done!'));

console.log('\nNext steps:');
Expand All @@ -206,9 +268,14 @@ export async function main() {
console.log(` ${i++}: ${bold(cyan(`cd ${relative}`))}`);
}

console.log(` ${i++}: ${bold(cyan('npm install'))} (or pnpm install, yarn, etc)`);
console.log(` ${i++}: ${bold(cyan('git init && git add -A && git commit -m "Initial commit"'))} (optional step)`);
console.log(` ${i++}: ${bold(cyan('npm run dev'))} (or pnpm, yarn, etc)`);
if (!supportedPM) {
console.log(` ${i++}: ${bold(cyan('npm install'))} (or pnpm install, yarn, etc)`);
console.log(` ${i++}: ${bold(cyan('npm run dev'))} (or pnpm, yarn, etc)`);
} else {
if (pm === 'yarn') console.log(` ${i++}: ${bold(cyan('yarn dev'))}`);
else if (pm === 'pnpm') console.log(` ${i++}: ${bold(cyan('pnpm run dev'))}`);
else console.log(` ${i++}: ${bold(cyan('npm run dev'))}`);
}

console.log(`\nTo close the dev server, hit ${bold(cyan('Ctrl-C'))}`);
console.log(`\nStuck? Visit us at ${cyan('https://astro.build/chat')}\n`);
Expand Down
Loading