Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

package-json.ts

102 lines2.9 KB

1import { render } from 'ejs'
2import { sortObject } from './utils.js'
3​
4import type { Options } from './types.js'
5​
6export function mergePackageJSON(
7 packageJSON: Record<string, any>,
8 overlayPackageJSON?: Record<string, any>,
9) {
10 return {
11 ...packageJSON,
12 ...(overlayPackageJSON || {}),
13 dependencies: {
14 ...packageJSON.dependencies,
15 ...(overlayPackageJSON?.dependencies || {}),
16 },
17 devDependencies: {
18 ...packageJSON.devDependencies,
19 ...(overlayPackageJSON?.devDependencies || {}),
20 },
21 scripts: {
22 ...packageJSON.scripts,
23 ...(overlayPackageJSON?.scripts || {}),
24 },
25 }
27​
28export function createPackageJSON(options: Options) {
29 let packageJSON = {
30 ...JSON.parse(JSON.stringify(options.framework.basePackageJSON)),
31 name: options.projectName,
32 }
33​
34 const additions: Array<Record<string, any> | undefined> = [
35 options.typescript
36 ? options.framework.optionalPackages.typescript
37 : undefined,
38 options.tailwind
39 ? options.framework.optionalPackages.tailwindcss
40 : undefined,
41 options.mode ? options.framework.optionalPackages[options.mode] : undefined,
42 ]
43 for (const addition of additions.filter(Boolean)) {
44 packageJSON = mergePackageJSON(packageJSON, addition)
45 }
46​
47 for (const addOn of options.chosenAddOns) {
48 let addOnPackageJSON = addOn.packageAdditions
49​
50 // Process EJS template if present
51 if (addOn.packageTemplate) {
52 const templateValues = {
53 packageManager: options.packageManager,
54 projectName: options.projectName,
55 typescript: options.typescript,
56 tailwind: options.tailwind,
57 js: options.typescript ? 'ts' : 'js',
58 jsx: options.typescript ? 'tsx' : 'jsx',
59 fileRouter: options.mode === 'file-router',
60 codeRouter: options.mode === 'code-router',
61 addOnEnabled: options.chosenAddOns.reduce<Record<string, boolean>>(
62 (acc, addon) => {
63 acc[addon.id] = true
64 return acc
65 },
66 {},
67 ),
68 addOnOption: options.addOnOptions,
69 addOns: options.chosenAddOns,
70 }
71​
72 try {
73 const renderedTemplate = render(addOn.packageTemplate, templateValues)
74 addOnPackageJSON = JSON.parse(renderedTemplate)
75 } catch (error) {
76 console.error(
77 `Error processing package.json.ejs for add-on ${addOn.id}:`,
78 error,
79 )
80 // Fall back to packageAdditions if template processing fails
81 }
82 }
83​
84 packageJSON = mergePackageJSON(packageJSON, addOnPackageJSON)
85 }
86​
87 if (options.starter) {
88 packageJSON = mergePackageJSON(
89 packageJSON,
90 options.starter.packageAdditions,
91 )
92 }
93​
94 packageJSON.dependencies = sortObject(
95 (packageJSON.dependencies ?? {}) as Record<string, string>,
96 )
97 packageJSON.devDependencies = sortObject(
98 (packageJSON.devDependencies ?? {}) as Record<string, string>,
99 )
100​
101 return packageJSON