Skip to content
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
59 changes: 59 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,65 @@ A shared package for create-rspack, create-rsbuild, create-rspress and create-rs
npm add create-rstack -D
```

## Features

### NPM Template Support

`create-rstack` supports using npm packages as templates, allowing users to create projects from custom templates published to npm.

#### Usage

```bash
# Using npm package name
npm create rsbuild@latest my-project -- --template my-template-package

# Using scoped package
npm create rsbuild@latest my-project -- --template @scope/template-package

# Using explicit npm: prefix
npm create rsbuild@latest my-project -- --template npm:my-template-package

# With specific version
npm create rsbuild@latest my-project -- --template my-template-package --template-version 1.2.3
```

#### Template Package Structure

Your npm template package should have one of the following structures:

```
my-template-package/
├── template/ # Preferred
│ ├── package.json
│ └── src/
├── templates/
│ └── app/ # Alternative
└── (root) # Fallback
├── package.json
└── src/
```

#### Caching Strategy

- Templates with `latest` version are always re-installed to ensure the latest version
- Specific versions are cached in `.temp-templates/` for faster reuse

#### API

```typescript
import {
isNpmTemplate,
resolveCustomTemplate,
resolveNpmTemplate,
} from 'create-rstack';

// Check if template input is an npm package
if (isNpmTemplate(templateInput)) {
// Resolve npm template to local path
const templatePath = resolveCustomTemplate(templateInput, version);
}
```

## Examples

| Project | Link |
Expand Down
83 changes: 68 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,21 @@ import deepmerge from 'deepmerge';
import minimist from 'minimist';
import { color, logger } from 'rslog';
import { x } from 'tinyexec';
import { isNpmTemplate, resolveCustomTemplate } from './template-manager.js';

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

export { autocomplete, groupMultiselect, multiselect, select, text };

// Export npm template utilities
export {
isNpmTemplate,
resolveCustomTemplate,
resolveNpmTemplate,
sanitizeCacheKey,
} from './template-manager.js';

function cancelAndExit() {
cancel('Operation cancelled.');
process.exit(0);
Expand Down Expand Up @@ -113,6 +122,8 @@ export type Argv = {
skill?: string | string[];
packageName?: string;
'package-name'?: string;
templateVersion?: string;
'template-version'?: string;
};

export const BUILTIN_TOOLS = ['eslint', 'rslint', 'biome', 'prettier'];
Expand Down Expand Up @@ -163,6 +174,7 @@ function logHelpMessage(
--tools <tool> add additional tools, comma separated
${skillsOptionLine} --override override files in target directory
--packageName <name> specify the package name
--template-version <ver> specify the npm template version

Available templates:
${templates.join(', ')}
Expand Down Expand Up @@ -341,6 +353,11 @@ const parseArgv = (processArgv: string[]) => {
argv.packageName = argv['package-name'];
}

// Handle template-version alias
if (argv['template-version']) {
argv.templateVersion = argv['template-version'];
}

return argv;
};

Expand Down Expand Up @@ -488,6 +505,27 @@ async function runSkillCommand(skills: ExtraSkill[], cwd: string) {
installationTaskLog.success(`Installed ${skillNoun} ${skillLabel}`);
}

function logNextStepsAndOutro(
noteInformation: string[] | undefined,
targetDir: string,
packageManager: string,
) {
const nextSteps = noteInformation
? noteInformation
: [
`1. ${color.cyan(`cd ${targetDir}`)}`,
`2. ${color.cyan('git init')} ${color.dim('(optional)')}`,
`3. ${color.cyan(`${packageManager} install`)}`,
`4. ${color.cyan(`${packageManager} run dev`)}`,
];

if (nextSteps.length) {
note(nextSteps.map((step) => color.reset(step)).join('\n'), 'Next steps');
}

outro('All set, happy coding!');
}

export async function create({
name,
root,
Expand Down Expand Up @@ -592,6 +630,35 @@ export async function create({
}

const templateName = await getTemplateName(argv);

const srcFolder = path.join(root, `template-${templateName}`);

// Handle npm template: only when the local template doesn't exist
// and the template input looks like an npm package
if (
typeof argv.template === 'string' &&
isNpmTemplate(argv.template) &&
!fs.existsSync(srcFolder)
) {
const templateVersion = argv.templateVersion ?? argv['template-version'];
const templatePath = resolveCustomTemplate(argv.template, templateVersion, {
cacheDir: root,
});

// Copy npm template directly to distFolder
copyFolder({
from: templatePath,
to: distFolder,
version,
packageName,
templateParameters,
skipFiles,
});

logNextStepsAndOutro(noteInformation, targetDir, packageManager);
return;
}

const tools = await getTools(argv, extraTools, templateName);
const skills = await getSkills(
argv,
Expand All @@ -601,7 +668,6 @@ export async function create({
multiselect,
);

const srcFolder = path.join(root, `template-${templateName}`);
const commonFolder = path.join(root, 'template-common');

if (!fs.existsSync(srcFolder)) {
Expand Down Expand Up @@ -734,20 +800,7 @@ export async function create({
);
}

const nextSteps = noteInformation
? noteInformation
: [
`1. ${color.cyan(`cd ${targetDir}`)}`,
`2. ${color.cyan('git init')} ${color.dim('(optional)')}`,
`3. ${color.cyan(`${packageManager} install`)}`,
`4. ${color.cyan(`${packageManager} run dev`)}`,
];

if (nextSteps.length) {
note(nextSteps.map((step) => color.reset(step)).join('\n'), 'Next steps');
}

outro('All set, happy coding!');
logNextStepsAndOutro(noteInformation, targetDir, packageManager);
}

function sortObjectKeys(obj: Record<string, unknown>) {
Expand Down
Loading