Skip to content

Commit

Permalink
feat: 🎸 add create pkg cli (#298)
Browse files Browse the repository at this point in the history
* feat: 🎸 add create pkg cli

* refactor: 💡 move to @ice/pkg

* chore: 🤖 publsih files to npm

* feat: 🎸 typo of docusaurus & refact

* refactor: 💡 refact code

* fix: 🐛 remove core.js

* ci: 🎡 pass ci

* fix: 🐛 generate material instead of projects

* fix: 🐛 remove generate project pkg

* chore: 🤖 version

* feat: 🎸 remove iceworks

* chore: 🤖 error in package.lock

* refactor: 💡 lint

* refactor: 💡 refact

* feat: 🎸 reduce inquirer
  • Loading branch information
maoxiaoke authored Mar 28, 2022
1 parent 6deb82f commit 16cd7c4
Show file tree
Hide file tree
Showing 31 changed files with 539 additions and 43 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ swc 编译选项。具体可参考 [swc 配置](https://swc.rs/docs/configuratio

### 组件预览

`@ice/pkg-cli` 依赖 [@ice/pkg-plugin-docusarus](https://github.com/ice-lab/component-next/tree/main/packages/plugin-docusarus) 插件支持编写文档和预览组件,所有文档默认存放至 `docs` 文件夹下。支持以 `.md``.mdx` 为后缀的文档。用法:
`@ice/pkg-cli` 依赖 [@ice/pkg-plugin-docusaurus](https://github.com/ice-lab/component-next/tree/main/packages/plugin-docusaurus) 插件支持编写文档和预览组件,所有文档默认存放至 `docs` 文件夹下。支持以 `.md``.mdx` 为后缀的文档。用法:

```shell
# 若存在 docs 文件夹,则默认启动文档预览;并启动 es/lib 编译
Expand Down Expand Up @@ -646,10 +646,10 @@ import MyComponent from 'my-component';

#### 插件配置

`@ice/pkg-plugin-docusarus` 插件接受如下配置:
`@ice/pkg-plugin-docusaurus` 插件接受如下配置:

```typescript
export interface PluginDocusarusOptions {
export interface PluginDocusaurusOptions {
/**
* 文档的 title,默认为 "飞冰组件"
*/
Expand Down Expand Up @@ -688,7 +688,7 @@ import { defineConfig } from '@ice/pkg-cli';

export default defineConfig({
plugins: [
['@ice/pkg-plugin-docusarus', {
['@ice/pkg-plugin-docusaurus', {
title: '标题'
}]
]
Expand Down
2 changes: 1 addition & 1 deletion examples/package/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export default defineConfig({
minify: false,
babelPlugins: ['transform-remove-console'],
plugins: [
'@ice/pkg-plugin-docusarus',
'@ice/pkg-plugin-docusaurus',
// './plugin.js',
],
sourceMaps: true,
Expand Down
3 changes: 2 additions & 1 deletion examples/package/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@ice/pkg-plugin-docusarus": "workspace: *",
"@ice/pkg-cli": "workspace: *",
"@ice/pkg-plugin-docusaurus": "workspace: *",
"babel-plugin-transform-remove-console": "^6.9.4",
"consola": "^2.15.3"
},
"author": "",
"license": "ISC",
"dependencies": {
"@docusaurus/preset-classic": "2.0.0-beta.17",
"core-js": "^3.21.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
Expand Down
Binary file removed examples/package/static/img/favicon.ico
Binary file not shown.
Binary file removed examples/package/static/img/logo.png
Binary file not shown.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
"scripts": {
"preinstall": "npx only-allow pnpm",
"setup": "rm -rf node_modules && rm -rf ./packages/*/node_modules && pnpm i --registry=https://registry.npmmirror.com && npm run build",
"build": "pnpm run clean && pnpm -r --filter ./packages --filter !./packages/plugin-docusarus run build && pnpm --filter ./packages/plugin-docusarus run build",
"build": "pnpm run clean && pnpm run build-ahead && pnpm run build-behind",
"build-ahead": "pnpm -r --filter ./packages/pkg-cli --filter ./packages/plugin-component run build",
"build-behind": "pnpm --parallel --filter ./packages --filter !./packages/pkg-cli --filter !./packages/plugin-component run build",
"clean": "rm -rf packages/*/lib",
"test": "vitest run",
"coverage": "vitest run --coverage",
Expand Down
9 changes: 9 additions & 0 deletions packages/create-pkg/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Changelog

## 1.0.1

- [fix] remove `@@appworks/cli`.

## 1.0.0

- init
13 changes: 13 additions & 0 deletions packages/create-pkg/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# @ice/create-pkg

Create pkg-cli projects by npm initing.

## Usage

```shell
$ npm init @ice/pkg component-name

# or with pnpm
$ pnpm init @ice/pkg component-name
```

32 changes: 32 additions & 0 deletions packages/create-pkg/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "@ice/create-pkg",
"version": "1.0.1",
"description": "npm init @ice/pkg",
"type": "module",
"exports": "./esnext/index.js",
"files": [
"es",
"esnext"
],
"bin": {
"create-pkg": "./esnext/index.js"
},
"scripts": {
"build": "pkg-cli build"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@ice/pkg-cli": "1.0.0-beta.3",
"typescript": "^4.5.4"
},
"dependencies": {
"@iceworks/generate-material": "^1.0.12",
"cac": "^6.7.12",
"consola": "^2.15.3",
"fs-extra": "^10.0.0",
"ice-npm-utils": "^3.0.2",
"inquirer": "^8.2.1",
"validate-npm-package-name": "^3.0.0"
}
}
13 changes: 13 additions & 0 deletions packages/create-pkg/src/checkEmpty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import fs from 'fs-extra';

export async function checkEmpty(dir: string): Promise<boolean> {
let files: string[] = fs.readdirSync(dir);
files = files.filter((filename) => {
return ['node_modules', '.git', '.DS_Store', '.iceworks-tmp', 'build', '.bzbconfig'].indexOf(filename) === -1;
});
if (files.length && files.length > 0) {
return false;
} else {
return true;
}
}
84 changes: 84 additions & 0 deletions packages/create-pkg/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/env node

import { fileURLToPath } from 'url';
import consola from 'consola';
import { cac } from 'cac';
import fs from 'fs-extra';
import path from 'path';
import inquirer from 'inquirer';
import { downloadMaterialTemplate, generateMaterial } from '@iceworks/generate-material';
import { checkEmpty } from './checkEmpty.js';
import { inquirPackageName } from './inquirPackageName.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const cli = cac('@ice/create-pkg');

(async () => {
cli.command('[...args]', 'Target dirname to generate', {
allowUnknownOptions: false,
ignoreOptionDefaultValue: true,
})
.action(async (args) => {
const targetDirname = args[0] ?? '.';

const dirPath = path.join(process.cwd(), targetDirname);
await create(dirPath, targetDirname);
});

cli.help();

const pkgPath = path.join(__dirname, '../package.json');
const { version } = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
consola.info('@ice/create-pkg version: ', version);

cli.version(version);

cli.parse(process.argv, { run: true });
})()
.catch((err) => {
consola.error(err);
process.exit(1);
});

async function create(dirPath: string, dirname: string): Promise<void> {
await fs.ensureDir(dirPath);
const empty = await checkEmpty(dirPath);

if (!empty) {
const { go } = await inquirer.prompt({
type: 'confirm',
name: 'go',
message:
'Files exist in the current directory already. Are you sure to continue ?',
default: false,
});
if (!go) process.exit(1);
}

const tempDir = path.join(dirPath, '.tmp');

await downloadMaterialTemplate(tempDir, '@ice/template-pkg-react');

const npmName = await inquirPackageName();

await generateMaterial({
rootDir: dirPath,
templateOptions: {
npmName,
},
materialTemplateDir: tempDir,
materialType: 'component',
});

await fs.remove(tempDir);

console.log();
console.log('Initialize component successfully.');
console.log();
console.log(` cd ${dirname}`);
console.log(' npm install');
console.log(' npm start');
console.log();
}

56 changes: 56 additions & 0 deletions packages/create-pkg/src/inquirPackageName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import inquirer from 'inquirer';
import { checkAliInternal } from 'ice-npm-utils';
import validateName from 'validate-npm-package-name';

function generateNpmName(name: string, npmScope?: string): string {
if (name.charAt(0) === '@') {
return name;
}

return npmScope ? `${npmScope}/${name}` : name;
}

export async function inquirPackageName() {
const isIntranet = checkAliInternal();

const { forIntranet } = await (isIntranet
? inquirer.prompt([
{
type: 'confirm',
message: 'generate components that are only available on the Intranet',
name: 'forIntranet',
},
])
: { forIntranet: false });

let npmScope = null;
if (forIntranet) {
npmScope = (await inquirer.prompt([
{
type: 'list',
message: 'please select the npm scope',
name: 'npmScope',
default: '@ali',
choices: ['@ali', '@alife', '@alipay', '@kaola'],
},
]))?.npmScope;
}

const { npmName } = await inquirer.prompt([
{
type: 'input',
name: 'npmName',
message: 'package name',
default: 'example-component',
validate: (value) => {
const name = generateNpmName(value, npmScope);
if (!validateName(name).validForNewPackages) {
return `NPM package name ${name} not validate, please retry`;
}
return true;
},
},
]);

return generateNpmName(npmName, npmScope);
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ice/pkg-plugin-docusarus",
"version": "1.0.0",
"name": "@ice/pkg-plugin-docusaurus",
"version": "1.0.0-beta.0",
"description": "Plugin for component previewing",
"main": "esnext/index.js",
"exports": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { fileURLToPath } from 'url';
import fs from 'fs-extra';
import hbs from 'handlebars';

import type { PluginDocusarusOptions } from './index.mjs';
import type { PluginDocusaurusOptions } from './index.mjs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export function configureDocusaurus(rootDir: string, params: PluginDocusarusOptions) {
export function configureDocusaurus(rootDir: string, params: PluginDocusaurusOptions) {
const templatePath = path.join(__dirname, './template/docusaurus.hbs');
const templateContents = fs.readFileSync(templatePath, 'utf-8');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@ import { fork } from 'child_process';
import { createRequire } from 'module';
import consola from 'consola';

import type { PluginDocusarusOptions } from './index.mjs';
import type { PluginDocusaurusOptions } from './index.mjs';

const require = createRequire(import.meta.url);

export const doc = (api, options: PluginDocusarusOptions) => {
export const doc = (api, options: PluginDocusaurusOptions) => {
const { context } = api;
const { rootDir, command } = context;

const maybeCustomPath = path.join(rootDir, 'docusaurus.config.js');
const docusaurusConfigFileExist = fs.pathExistsSync(maybeCustomPath);

if (docusaurusConfigFileExist) {
consola.warn('PLUGIN-DOCUSARUS', 'Found docusaurus.config.js in current project. And you should configure docusaurus by yourself.');
consola.warn('PLUGIN-DOCUSAURUS', 'Found docusaurus.config.js in current project. And you should configure docusaurus by yourself.');
}

const binPath = require.resolve('@docusaurus/core/bin/docusaurus.mjs');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { configureDocusaurus } from './configureDocusaurus.mjs';

import type { ComponentPlugin } from '@ice/pkg-cli';

export interface PluginDocusarusOptions {
export interface PluginDocusaurusOptions {
/**
* Title for your doc.
*/
Expand Down Expand Up @@ -34,18 +34,18 @@ export interface PluginDocusarusOptions {
port?: number;
}

const defaultOptions: PluginDocusarusOptions = {
const defaultOptions: PluginDocusaurusOptions = {
title: '飞冰组件',
url: 'https://your-docusaurus-test-site.com',
baseUrl: '/',
favicon: 'img/favicon.ico',
navBarLogo: 'img/logo.png',
favicon: 'https://img.alicdn.com/imgextra/i2/O1CN01jUf9ZP1aKwVvEc58W_!!6000000003312-73-tps-160-160.ico',
navBarLogo: 'https://img.alicdn.com/imgextra/i1/O1CN01lZTSIX1j7xpjIQ3fJ_!!6000000004502-2-tps-160-160.png',
navBarTitle: '飞冰组件',
port: 4444,
};

// @ts-ignore
const plugin: ComponentPlugin = (api, options: PluginDocusarusOptions) => {
const plugin: ComponentPlugin = (api, options: PluginDocusaurusOptions) => {
const {
onHook,
context,
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion
const extractCode = require('@ice/pkg-plugin-docusarus/remark/extractCode');
const extractCode = require('@ice/pkg-plugin-docusaurus/remark/extractCode');

/** @type {import('@docusaurus/types').Config} */
const config = {
Expand All @@ -13,7 +13,7 @@ const config = {
favicon: '{{favicon}}',

plugins: [
require.resolve('@ice/pkg-plugin-docusarus/plugin.js'),
require.resolve('@ice/pkg-plugin-docusaurus/plugin.js'),
],

presets: [
Expand All @@ -28,7 +28,7 @@ const config = {
routeBasePath: '/',
},
theme: {
customCss: require.resolve('@ice/pkg-plugin-docusarus/css/custom.css'),
customCss: require.resolve('@ice/pkg-plugin-docusaurus/css/custom.css'),
},
}),
],
Expand Down
9 changes: 9 additions & 0 deletions packages/plugin-docusaurus/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"baseUrl": "./",
"rootDir": "src",
"outDir": "lib"
},
"include": ["src"]
}
Loading

0 comments on commit 16cd7c4

Please sign in to comment.