Skip to content

Commit

Permalink
feat: cli bin init and NX integrated (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
Timeless0911 authored Jun 18, 2024
1 parent 16c28b3 commit 553bef9
Show file tree
Hide file tree
Showing 16 changed files with 925 additions and 40 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ node_modules/

dist/
dist-types/
compiled/
coverage/
doc_build/
playwright-report/

.vscode/**/*
!.vscode/settings.json
!.vscode/extensions.json
.idea/
.idea/
.nx/
32 changes: 32 additions & 0 deletions nx.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"namedInputs": {
"default": ["{projectRoot}/src/**/*"],
"build": [
"default",
"!{projectRoot}/**/*.{md,mdx}",
"{projectRoot}/tsconfig.json",
"{projectRoot}/package.json",
"{projectRoot}/modern.config.*",
"{projectRoot}/scripts/**/*"
],
"prebundle": [
"{projectRoot}/package.json",
"{projectRoot}/prebundle.config.mjs"
]
},
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build", "prebundle"],
"inputs": ["build", "^build"],
"outputs": ["{projectRoot}/dist", "{projectRoot}/dist-types"]
},
"prebundle": {
"cache": true,
"inputs": ["prebundle"],
"outputs": ["{projectRoot}/compiled"]
}
},
"defaultBase": "main"
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
"name": "rslib-monorepo",
"private": true,
"scripts": {
"build": "pnpm -r --filter='./packages/*' run build",
"build": "cross-env NX_DAEMON=false nx run-many -t build --parallel=10",
"check-dependency-version": "check-dependency-version-consistency .",
"lint": "biome check . --diagnostic-level=warn",
"prebundle": "nx run-many -t prebundle",
"prepare": "pnpm run build && simple-git-hooks",
"sort-package-json": "npx sort-package-json \"packages/*/package.json\"",
"test:artifact": "vitest run --project artifact",
Expand All @@ -28,6 +29,7 @@
"check-dependency-version-consistency": "^4.1.0",
"cross-env": "^7.0.3",
"nano-staged": "^0.8.0",
"nx": "^19.3.0",
"prettier": "^3.2.4",
"prettier-plugin-packagejson": "^2.5.0",
"simple-git-hooks": "^2.10.0",
Expand Down
10 changes: 8 additions & 2 deletions packages/core/bin/rslib.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
#!/usr/bin/env node
import { runCli } from '../dist/index.js';
import { logger, prepareCli, runCli } from '../dist/index.js';

async function main() {
runCli();
prepareCli();

try {
runCli();
} catch (err) {
logger.error(err);
}
}

main();
32 changes: 32 additions & 0 deletions packages/core/modern.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,24 @@
import { defineConfig, moduleTools } from '@modern-js/module-tools';
import prebundleConfig from './prebundle.config.mjs';

const externals = ['@rsbuild/core', /[\\/]compiled[\\/]/, /node:/];
const define = {
RSLIB_VERSION: require('./package.json').version,
};

const aliasCompiledPlugin = {
name: 'alias-compiled-plugin',
setup(build) {
const { dependencies } = prebundleConfig;
for (const item of dependencies) {
const depName = typeof item === 'string' ? item : item.name;
build.onResolve({ filter: new RegExp(`^${depName}$`) }, () => ({
path: `../compiled/${depName}/index.js`,
external: true,
}));
}
},
};

export default defineConfig({
plugins: [moduleTools()],
Expand All @@ -8,14 +28,26 @@ export default defineConfig({
target: 'es2020',
buildType: 'bundle',
autoExtension: true,
externals,
dts: false,
define,
esbuildOptions(options) {
options.plugins?.unshift(aliasCompiledPlugin);
return options;
},
},
{
format: 'esm',
target: 'es2020',
buildType: 'bundle',
autoExtension: true,
externals,
dts: false,
define,
esbuildOptions(options) {
options.plugins?.unshift(aliasCompiledPlugin);
return options;
},
},
{
buildType: 'bundleless',
Expand Down
16 changes: 11 additions & 5 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,25 @@
"files": [
"bin",
"dist",
"dist-types"
"dist-types",
"compiled"
],
"scripts": {
"build": "modern build",
"dev": "modern build --watch"
"dev": "modern build --watch",
"prebundle": "prebundle"
},
"dependencies": {
"@rsbuild/core": "0.6.2",
"@rsbuild/shared": "0.6.2"
"@rsbuild/core": "0.6.2"
},
"devDependencies": {
"@rslib/tsconfig": "workspace:*",
"commander": "^12.0.0",
"@types/fs-extra": "^11.0.4",
"commander": "^12.1.0",
"fs-extra": "^11.2.0",
"picocolors": "1.0.1",
"prebundle": "1.1.0",
"rslog": "^1.2.2",
"typescript": "^5.4.5"
},
"engines": {
Expand Down
27 changes: 27 additions & 0 deletions packages/core/prebundle.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// @ts-check
import { join } from 'node:path';
import fs from 'fs-extra';

/**
* Tip: please add the prebundled packages to `tsconfig.json#paths`.
*/

/** @type {import('prebundle').Config} */
export default {
externals: {
typescript: 'typescript',
},
dependencies: [
'commander',
{
name: 'picocolors',
beforeBundle({ depPath }) {
const typesFile = join(depPath, 'types.ts');
// Fix type bundle
if (fs.existsSync(typesFile)) {
fs.renameSync(typesFile, join(depPath, 'types.d.ts'));
}
},
},
],
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { program } from 'commander';
import { build } from './build';
import type { RslibConfig } from './types';
import { build } from '../build';
import type { RslibConfig } from '../types';

export function runCli() {
program.name('rslib').usage('<command> [options]').version(RSLIB_VERSION);

const buildCommand = program.command('build');

buildCommand
Expand Down
27 changes: 27 additions & 0 deletions packages/core/src/cli/prepare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { logger } from '../utils/logger';

function initNodeEnv() {
if (!process.env.NODE_ENV) {
const command = process.argv[2] ?? '';
process.env.NODE_ENV = ['build'].includes(command)
? 'production'
: 'development';
}
}

export function prepareCli() {
initNodeEnv();

// Print a blank line to keep the greet log nice.
// Some package managers automatically output a blank line, some do not.
const { npm_execpath } = process.env;
if (
!npm_execpath ||
npm_execpath.includes('npx-cli.js') ||
npm_execpath.includes('.bun')
) {
console.log();
}

logger.greet(` ${`Rslib v${RSLIB_VERSION}`}\n`);
}
1 change: 1 addition & 0 deletions packages/core/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare const RSLIB_VERSION;
14 changes: 8 additions & 6 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
/**
* The project structure and implementation of Rslib is a placeholder.
* Only to setup the basic infrastructure workflow.
*/

export { build } from './build';
export { runCli } from './cli';
export { runCli } from './cli/commands';
export { prepareCli } from './cli/prepare';

export * from './utils/logger';
export * from './utils/helper';

export type { RslibConfig } from './types';

export const version = RSLIB_VERSION;
3 changes: 3 additions & 0 deletions packages/core/src/utils/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import color from 'picocolors';

export { color };
39 changes: 39 additions & 0 deletions packages/core/src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { type Logger, logger } from 'rslog';
import { color } from './helper';

// setup the logger level
if (process.env.DEBUG) {
logger.level = 'verbose';
}

export const isDebug = () => {
if (!process.env.DEBUG) {
return false;
}

logger.level = 'verbose'; // support `process.env.DEBUG` in e2e
const values = process.env.DEBUG.toLocaleLowerCase().split(',');
return ['rslib', 'rsbuild', 'builder', '*'].some((key) =>
values.includes(key),
);
};

function getTime() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');

return `${hours}:${minutes}:${seconds}`;
}

export const debug = (message: string | (() => string)) => {
if (isDebug()) {
const result = typeof message === 'string' ? message : message();
const time = color.gray(`${getTime()}`);
logger.debug(`${time} ${result}`);
}
};

export { logger };
export type { Logger };
6 changes: 5 additions & 1 deletion packages/core/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
"declaration": true,
"declarationDir": "./dist-types",
"module": "ESNext",
"moduleResolution": "Bundler"
"moduleResolution": "Bundler",
"paths": {
"commander": ["./compiled/commander"],
"picocolors": ["./compiled/picocolors"]
}
},
"include": ["src"],
"exclude": ["**/node_modules"]
Expand Down
Loading

0 comments on commit 553bef9

Please sign in to comment.