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 all 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': patch
---

Add peer dependencies to package.json
1 change: 1 addition & 0 deletions packages/create-astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"degit": "^2.8.4",
"kleur": "^4.1.4",
"node-fetch": "^3.2.3",
"ora": "^6.1.0",
"prompts": "^2.4.2",
"yargs-parser": "^21.0.1"
},
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' },
},
];
50 changes: 34 additions & 16 deletions packages/create-astro/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ 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 { FRAMEWORKS, COUNTER_COMPONENTS, Integration } from './frameworks.js';
import { TEMPLATES } from './templates.js';
import { createConfig } from './config.js';
import { logger, defaultLogLevel } from './logger.js';
Expand Down Expand Up @@ -36,8 +37,9 @@ export async function main() {
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 +59,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 +89,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 +103,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 +131,7 @@ export async function main() {
)
);
}
spinner.fail();
process.exit(1);
}

Expand All @@ -154,14 +158,28 @@ 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: [string, string][] = [[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);
// merge and sort dependencies
packageJSON.devDependencies = { ...(packageJSON.devDependencies ?? {}), ...Object.fromEntries(integrationEntries) };
packageJSON.devDependencies = Object.fromEntries(Object.entries(packageJSON.devDependencies).sort((a, b) => a[0].localeCompare(b[0])));
await fs.promises.writeFile(fileLoc, JSON.stringify(packageJSON, undefined, 2));
break;
}
Expand All @@ -174,8 +192,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,11 +214,11 @@ export async function main() {
await fs.promises.writeFile(pageFileLoc, newContent);
}

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

console.log('\nNext steps:');
let i = 1;

const relative = path.relative(process.cwd(), cwd);
if (relative !== '') {
console.log(` ${i++}: ${bold(cyan(`cd ${relative}`))}`);
Expand Down
Loading