feat(v2): docusaurus init (#1516)

* feat(v2): docusaurus init

* change logo
This commit is contained in:
Endi 2019-05-25 14:16:42 +07:00 committed by GitHub
parent 64a86f6264
commit 99a58263ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 454 additions and 21 deletions

View File

@ -15,10 +15,8 @@ import withBaseUrl from '@docusaurus/withBaseUrl';
function Footer() {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
const {
themeConfig: {footer},
} = siteConfig;
const {themeConfig = {}} = siteConfig;
const {footer} = themeConfig;
if (!footer) {
return null;

View File

@ -36,11 +36,9 @@ function NavLink(props) {
function Navbar() {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
const {
baseUrl,
themeConfig: {algolia, navbar = {}},
} = siteConfig;
const {title, logo, links} = navbar;
const {baseUrl, themeConfig = {}} = siteConfig;
const {algolia, navbar = {}} = themeConfig;
const {title, logo, links = []} = navbar;
return (
<nav className="navbar navbar--light navbar--fixed-top">

View File

@ -62,15 +62,15 @@ program
});
program
.command('init [projectDir]')
.command('init [siteName] [template] [rootDir]')
.description('Initialize website')
.action((projectDir = '.') => {
wrapCommand(init)(path.resolve(projectDir));
.action((siteName, template, rootDir = '.') => {
wrapCommand(init)(path.resolve(rootDir), siteName, template);
});
program
.command('deploy [siteDir]')
.description('deploy website')
.description('Deploy website to GitHub pages')
.action((siteDir = '.') => {
wrapCommand(deploy)(path.resolve(siteDir));
});

View File

@ -51,6 +51,7 @@
"globby": "^9.1.0",
"html-webpack-plugin": "^4.0.0-beta.5",
"import-fresh": "^3.0.0",
"inquirer": "^6.3.1",
"lodash": "^4.17.11",
"mini-css-extract-plugin": "^0.4.1",
"nprogress": "^0.2.0",

View File

@ -5,15 +5,188 @@
* LICENSE file in the root directory of this source tree.
*/
import {CLIOptions} from '../server';
import chalk from 'chalk';
import fs from 'fs-extra';
import shell from 'shelljs';
import inquirer from 'inquirer';
import path from 'path';
import _ from 'lodash';
import {execSync} from 'child_process';
function hasYarn() {
try {
execSync('yarnpkg --version', {stdio: 'ignore'});
return true;
} catch (e) {
return false;
}
}
function isValidGitRepoUrl(gitRepoUrl) {
return gitRepoUrl.startsWith('https://') || gitRepoUrl.startsWith('git@');
}
async function updatePkg(pkgPath, obj) {
const content = await fs.readFile(pkgPath, 'utf-8');
const pkg = JSON.parse(content);
const newPkg = Object.assign(pkg, obj);
await fs.outputFile(pkgPath, JSON.stringify(newPkg, null, 2));
}
export async function init(
projectDir: string,
cliOptions: CLIOptions = {},
rootDir: string,
siteName?: string,
reqTemplate?: string,
): Promise<void> {
console.log('Init command invoked ...');
console.log(projectDir);
console.log(cliOptions);
const useYarn = hasYarn();
const templatesDir = path.resolve(__dirname, '../../templates');
const templates = fs
.readdirSync(templatesDir)
.filter(d => !d.startsWith('.') && !d.startsWith('README'));
// TODO
const gitChoice = 'Git repository';
const templateChoices = [...templates, gitChoice];
let name = siteName;
// Prompt if siteName is not passed from CLI
if (!name) {
const answers = await inquirer.prompt({
type: 'input',
name: 'name',
message: 'What should we name this site?',
default: 'website',
});
name = answers.name;
}
if (!name) {
throw new Error(chalk.red('A site name is required'));
}
const dest = path.resolve(rootDir, name);
if (fs.existsSync(dest)) {
throw new Error(`Directory already exists at ${dest} !`);
}
let template = reqTemplate;
// Prompt if template is not provided from CLI
if (!template) {
const answers = await inquirer.prompt({
type: 'list',
name: 'template',
message: 'Select a template below...',
choices: templateChoices,
});
template = answers.template;
}
// If user choose Git repository, we'll prompt for the url
if (template === gitChoice) {
const {gitRepoUrl} = await inquirer.prompt({
type: 'input',
name: 'gitRepoUrl',
validate: url => {
if (url && isValidGitRepoUrl(url)) {
return true;
}
return chalk.red(`Invalid repository URL`);
},
message:
'Enter a repository URL from GitHub, BitBucket, GitLab, or any other public repo. \n(e.g: https://github.com/ownerName/repoName.git)',
});
template = gitRepoUrl;
}
console.log();
console.log(chalk.cyan('Creating new Docusaurus project ...'));
console.log();
if (template && isValidGitRepoUrl(template)) {
console.log(`Cloning Git template: ${chalk.cyan(template)}`);
if (
shell.exec(`git clone --recursive ${template} ${dest}`, {silent: true})
.code !== 0
) {
throw new Error(chalk.red(`Cloning Git template: ${template} failed!`));
}
} else if (template && templates.includes(template)) {
// Docusaurus templates
try {
await fs.copy(path.resolve(templatesDir, template), dest);
} catch (err) {
console.log(
`Copying Docusaurus template: ${chalk.cyan(template)} failed!`,
);
throw err;
}
} else {
throw new Error('Invalid template');
}
// Update package.json info
try {
await updatePkg(path.join(dest, 'package.json'), {
name: _.kebabCase(name),
version: '0.0.0',
private: true,
});
} catch (err) {
console.log(chalk.red('Failed to update package.json'));
throw err;
}
// We need to Rename the gitignore file to .gitignore
if (
!fs.pathExistsSync(path.join(dest, '.gitignore')) &&
fs.pathExistsSync(path.join(dest, 'gitignore'))
) {
await fs.move(path.join(dest, 'gitignore'), path.join(dest, '.gitignore'));
}
if (fs.pathExistsSync(path.join(dest, 'gitignore'))) {
fs.removeSync(path.join(dest, 'gitignore'));
}
const pkgManager = useYarn ? 'yarn' : 'npm';
console.log(`Installing dependencies with: ${chalk.cyan(pkgManager)}`);
// we use execSync instead of shell.exec to hide installation output
try {
execSync(`cd "${name}" && ${useYarn ? 'yarn' : 'npm install'}`);
} catch (err) {
console.log(chalk.red('Installation failed'));
throw err;
}
console.log();
// Display the most elegant way to cd.
let cdpath;
if (path.join(process.cwd(), name) === dest) {
cdpath = name;
} else {
cdpath = path.relative(process.cwd(), dest);
}
console.log();
console.log(`Success! Created ${chalk.cyan(cdpath)}`);
console.log('Inside that directory, you can run several commands:');
console.log();
console.log(chalk.cyan(` ${pkgManager} start`));
console.log(' Starts the development server.');
console.log();
console.log(chalk.cyan(` ${pkgManager} ${useYarn ? '' : 'run '}build`));
console.log(' Bundles the app into static files for production.');
console.log();
console.log(chalk.cyan(` ${pkgManager} deploy`));
console.log(' Publish website to GitHub pages.');
console.log();
console.log('We suggest that you begin by typing:');
console.log();
console.log(chalk.cyan(' cd'), cdpath);
console.log(` ${chalk.cyan(`${pkgManager} start`)}`);
console.log();
console.log('Happy hacking!');
}

View File

@ -0,0 +1,16 @@
---
title: Hello
author: Endilie Yacop Sucipto
authorTitle: Maintainer of Docusaurus
authorURL: https://github.com/endiliey
authorImageURL: https://avatars1.githubusercontent.com/u/17883920?s=460&v=4
authorTwitter: endiliey
---
Welcome to this blog. This blog is created with [**Docusaurus 2 alpha**](https://v2.docusaurus.io/).
<!--truncate-->
This is a test post.
A whole bunch of other information.

View File

@ -0,0 +1,9 @@
---
title: Welcome
author: Yangshun
authorURL: https://github.com/yangshun
authorImageURL: https://avatars0.githubusercontent.com/u/1315101?s=400&v=4
authorTwitter: yangshunz
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet

View File

@ -0,0 +1,17 @@
---
id: doc1
title: Latin-ish
sidebar_label: Example Page
---
I can write content using [GitHub-flavored Markdown syntax](https://github.github.com/gfm/)
## Markdown Syntax
**Bold** _italic_ `code` [Links](#url)
> Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse id sem consectetuer libero luctus adipiscing.
- Hey
- Ho
- Let's Go

View File

@ -0,0 +1,7 @@
---
id: doc2
title: document number 2
---
This is a link to [another document.](doc3.md)
This is a link to an [external page.](http://www.example.com)

View File

@ -0,0 +1,13 @@
---
id: doc3
title: This is document number 3
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ac euismod odio, eu consequat dui. Nullam molestie consectetur risus id imperdiet. Proin sodales ornare turpis, non mollis massa ultricies id. Nam at nibh scelerisque, feugiat ante non, dapibus tortor. Vivamus volutpat diam quis tellus elementum bibendum. Praesent semper gravida velit quis aliquam. Etiam in cursus neque. Nam lectus ligula, malesuada et mauris a, bibendum faucibus mi. Phasellus ut interdum felis. Phasellus in odio pulvinar, porttitor urna eget, fringilla lectus. Aliquam sollicitudin est eros. Mauris consectetur quam vitae mauris interdum hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis et egestas libero, imperdiet faucibus ipsum. Sed posuere eget urna vel feugiat. Vivamus a arcu sagittis, fermentum urna dapibus, congue lectus. Fusce vulputate porttitor nisl, ac cursus elit volutpat vitae. Nullam vitae ipsum egestas, convallis quam non, porta nibh. Morbi gravida erat nec neque bibendum, eu pellentesque velit posuere. Fusce aliquam erat eu massa eleifend tristique.
Sed consequat sollicitudin ipsum eget tempus. Integer a aliquet velit. In justo nibh, pellentesque non suscipit eget, gravida vel lacus. Donec odio ante, malesuada in massa quis, pharetra tristique ligula. Donec eros est, tristique eget finibus quis, semper non nisl. Vivamus et elit nec enim ornare placerat. Sed posuere odio a elit cursus sagittis.
Phasellus feugiat purus eu tortor ultrices finibus. Ut libero nibh, lobortis et libero nec, dapibus posuere eros. Sed sagittis euismod justo at consectetur. Nulla finibus libero placerat, cursus sapien at, eleifend ligula. Vivamus elit nisl, hendrerit ac nibh eu, ultrices tempus dui. Nam tellus neque, commodo non rhoncus eu, gravida in risus. Nullam id iaculis tortor.
Nullam at odio in sem varius tempor sit amet vel lorem. Etiam eu hendrerit nisl. Fusce nibh mauris, vulputate sit amet ex vitae, congue rhoncus nisl. Sed eget tellus purus. Nullam tempus commodo erat ut tristique. Cras accumsan massa sit amet justo consequat eleifend. Integer scelerisque vitae tellus id consectetur.

View File

@ -0,0 +1,6 @@
---
id: doc4
title: Other Document
---
this is another document

View File

@ -0,0 +1,6 @@
---
id: doc5
title: Fifth Document
---
Another one

View File

@ -0,0 +1,79 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
module.exports = {
title: 'My site',
tagline: 'A website for testing',
url: 'https://your-docusaurus-test-site.com',
baseUrl: '/',
favicon: 'img/favicon.ico',
themeConfig: {
navbar: {
title: 'My site',
logo: {
alt: 'My site Logo',
src: 'img/logo.svg',
},
links: [
{to: 'docs/doc1', label: 'Docs', position: 'left'},
{to: 'blog', label: 'Blog', position: 'left'},
{
href: 'https://github.com/facebook/docusaurus',
label: 'GitHub',
position: 'right',
},
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{
label: 'Docs',
to: 'docs/doc1',
},
],
},
{
title: 'Community',
items: [
{
label: 'Discord',
href: 'https://discordapp.com/invite/docusaurus',
},
],
},
{
title: 'Social',
items: [
{
label: 'Blog',
to: 'blog',
},
],
},
],
logo: {
alt: 'Facebook Open Source Logo',
src: 'https://docusaurus.io/img/oss_logo.png',
},
copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`,
},
},
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.json'),
},
},
],
],
};

View File

@ -0,0 +1,20 @@
# dependencies
/node_modules
# production
/build
# generated files
.docusaurus
.cache-loader
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -0,0 +1,16 @@
{
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy"
},
"dependencies": {
"@docusaurus/core": "^2.0.0-alpha.16",
"@docusaurus/preset-classic": "^2.0.0-alpha.16",
"react": "^16.8.4",
"react-dom": "^16.8.4"
}
}

View File

@ -0,0 +1,30 @@
/* TODO: remove this css because it's only temporary until we revamp index.js */
.App {
text-align: center;
margin-bottom: 2rem;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none;
}
.App-header {
min-height: 50vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: black;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@ -0,0 +1,33 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '@theme/Layout';
import withBaseUrl from '@docusaurus/withBaseUrl';
import './index.css';
/* Note that this is only temporary. TODO: better welcome screen */
function Home() {
return (
<Layout title="Hello">
<div className="App">
<header className="App-header">
<img
src={withBaseUrl('img/logo.svg')}
className="App-logo"
alt="logo"
/>
<p>
Edit <code>pages/index.js</code> and save to reload.
</p>
</header>
</div>
</Layout>
);
}
export default Home;

View File

@ -0,0 +1,10 @@
{
"docs": {
"Docusaurus": ["doc1"],
"First Category": ["doc2"],
"Second Category": ["doc3"]
},
"docs-other": {
"First Category": ["doc4", "doc5"]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 B

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.3 KiB

View File

@ -7398,7 +7398,7 @@ inquirer@6.2.2:
strip-ansi "^5.0.0"
through "^2.3.6"
inquirer@^6.2.0:
inquirer@^6.2.0, inquirer@^6.3.1:
version "6.3.1"
resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-6.3.1.tgz#7a413b5e7950811013a3db491c61d1f3b776e8e7"
integrity sha512-MmL624rfkFt4TG9y/Jvmt8vdmOo836U7Y0Hxr2aFk3RelZEGX4Igk0KabWrcaaZaTv9uzglOqWh1Vly+FAWAXA==