From 8231ef933c293147ee7e701ac4cffc6e329194b8 Mon Sep 17 00:00:00 2001 From: Katerina Skroumpelou Date: Wed, 6 Sep 2023 11:14:42 +0300 Subject: [PATCH] feat(vue): init and lib generators --- docs/map.json | 14 + docs/shared/packages/vue/vue-plugin.md | 60 ++ packages/vue/docs/.gitkeep | 0 packages/vue/generators.json | 35 +- packages/vue/src/generators/.gitkeep | 0 packages/vue/src/generators/init/init.spec.ts | 27 + packages/vue/src/generators/init/init.ts | 70 ++ packages/vue/src/generators/init/schema.d.ts | 9 + packages/vue/src/generators/init/schema.json | 43 + .../src/generators/library/files/README.md | 7 + .../library/files/package.json__tmpl__ | 12 + .../library/files/src/index.ts__tmpl__ | 0 .../library/files/tsconfig.lib.json__tmpl__ | 23 + .../library/files/tsconfig.node.json__tmpl__ | 16 + .../files/tsconfig.vitest.json__tmpl__ | 9 + .../vue/src/generators/library/lib/.gitkeep | 0 .../src/generators/library/lib/add-linting.ts | 45 + .../generators/library/lib/create-files.ts | 49 ++ .../library/lib/normalize-options.spec.ts | 103 +++ .../library/lib/normalize-options.ts | 86 ++ .../src/generators/library/library.spec.ts | 818 ++++++++++++++++++ .../vue/src/generators/library/library.ts | 150 ++++ .../vue/src/generators/library/schema.d.ts | 41 + .../vue/src/generators/library/schema.json | 150 ++++ packages/vue/src/migrations/.gitkeep | 0 packages/vue/src/utils/.gitkeep | 0 packages/vue/src/utils/create-ts-config.ts | 76 ++ packages/vue/src/utils/lint.ts | 17 + packages/vue/src/utils/versions.ts | 7 + 29 files changed, 1866 insertions(+), 1 deletion(-) create mode 100644 docs/shared/packages/vue/vue-plugin.md create mode 100644 packages/vue/docs/.gitkeep create mode 100644 packages/vue/src/generators/.gitkeep create mode 100644 packages/vue/src/generators/init/init.spec.ts create mode 100755 packages/vue/src/generators/init/init.ts create mode 100644 packages/vue/src/generators/init/schema.d.ts create mode 100644 packages/vue/src/generators/init/schema.json create mode 100644 packages/vue/src/generators/library/files/README.md create mode 100644 packages/vue/src/generators/library/files/package.json__tmpl__ create mode 100644 packages/vue/src/generators/library/files/src/index.ts__tmpl__ create mode 100644 packages/vue/src/generators/library/files/tsconfig.lib.json__tmpl__ create mode 100644 packages/vue/src/generators/library/files/tsconfig.node.json__tmpl__ create mode 100644 packages/vue/src/generators/library/files/tsconfig.vitest.json__tmpl__ create mode 100644 packages/vue/src/generators/library/lib/.gitkeep create mode 100644 packages/vue/src/generators/library/lib/add-linting.ts create mode 100644 packages/vue/src/generators/library/lib/create-files.ts create mode 100644 packages/vue/src/generators/library/lib/normalize-options.spec.ts create mode 100644 packages/vue/src/generators/library/lib/normalize-options.ts create mode 100644 packages/vue/src/generators/library/library.spec.ts create mode 100644 packages/vue/src/generators/library/library.ts create mode 100644 packages/vue/src/generators/library/schema.d.ts create mode 100644 packages/vue/src/generators/library/schema.json create mode 100644 packages/vue/src/migrations/.gitkeep create mode 100644 packages/vue/src/utils/.gitkeep create mode 100644 packages/vue/src/utils/create-ts-config.ts create mode 100644 packages/vue/src/utils/lint.ts create mode 100644 packages/vue/src/utils/versions.ts diff --git a/docs/map.json b/docs/map.json index 773732fc8d6786..245917fe4e136b 100644 --- a/docs/map.json +++ b/docs/map.json @@ -2069,6 +2069,20 @@ } ] }, + { + "name": "vue", + "id": "vue", + "description": "Vue package.", + "itemList": [ + { + "id": "overview", + "path": "/packages/vue", + "name": "Overview of the Nx Vue Plugin", + "description": "The Nx Plugin for Vue contains generators for managing Vue applications and libraries within an Nx workspace. This page also explains how to configure Vue on your Nx workspace.", + "file": "shared/packages/vue/vue-plugin" + } + ] + }, { "name": "webpack", "id": "webpack", diff --git a/docs/shared/packages/vue/vue-plugin.md b/docs/shared/packages/vue/vue-plugin.md new file mode 100644 index 00000000000000..b0a95347fac059 --- /dev/null +++ b/docs/shared/packages/vue/vue-plugin.md @@ -0,0 +1,60 @@ +--- +title: Overview of the Nx Vue Plugin +description: The Nx Plugin for Vue contains generators for managing Vue applications and libraries within an Nx workspace. This page also explains how to configure Vue on your Nx workspace. +--- + +The Nx plugin for [Vue](https://vuejs.org/). + +## Setting up a new Nx workspace with Vue + +You can create a new workspace that uses Vue with one of the following commands: + +- Generate a new monorepo with a Vue app set up with Vue + +```shell +npx create-nx-workspace@latest --preset=vue +``` + +## Add Vue to an existing workspace + +There is a number of ways to use Vue in your existing workspace. + +### Install the `@nx/vue` plugin + +{% tabs %} +{% tab label="npm" %} + +```shell +npm install -D @nx/vue +``` + +{% /tab %} +{% tab label="yarn" %} + +```shell +yarn add -D @nx/vue +``` + +{% /tab %} +{% tab label="pnpm" %} + +```shell +pnpm install -D @nx/vue +``` + +{% /tab %} +{% /tabs %} + +### Generate a new project using Vue + +To generate a Vue application, run the following: + +```bash +nx g @nx/vue:app my-app +``` + +To generate a Vue library, run the following: + +```bash +nx g @nx/vue:lib my-lib +``` diff --git a/packages/vue/docs/.gitkeep b/packages/vue/docs/.gitkeep new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/packages/vue/generators.json b/packages/vue/generators.json index f07d4711fb3fc1..2ec66ee01b3471 100644 --- a/packages/vue/generators.json +++ b/packages/vue/generators.json @@ -1,5 +1,38 @@ { "name": "Nx Vue", "version": "0.1", - "generators": {} + "schematics": { + "init": { + "factory": "./src/generators/init/init#vueInitSchematic", + "schema": "./src/generators/init/schema.json", + "description": "Initialize the `@nrwl/vue` plugin.", + "aliases": ["ng-add"], + "hidden": true + }, + + "library": { + "factory": "./src/generators/library/library#librarySchematic", + "schema": "./src/generators/library/schema.json", + "aliases": ["lib"], + "x-type": "library", + "description": "Create a Vue library." + } + }, + "generators": { + "init": { + "factory": "./src/generators/init/init#vueInitSchematic", + "schema": "./src/generators/init/schema.json", + "description": "Initialize the `@nrwl/vue` plugin.", + "aliases": ["ng-add"], + "hidden": true + }, + + "library": { + "factory": "./src/generators/library/library#libraryGeneratorInternal", + "schema": "./src/generators/library/schema.json", + "aliases": ["lib"], + "x-type": "library", + "description": "Create a Vue library." + } + } } diff --git a/packages/vue/src/generators/.gitkeep b/packages/vue/src/generators/.gitkeep new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/packages/vue/src/generators/init/init.spec.ts b/packages/vue/src/generators/init/init.spec.ts new file mode 100644 index 00000000000000..b6a5e4eb5945ee --- /dev/null +++ b/packages/vue/src/generators/init/init.spec.ts @@ -0,0 +1,27 @@ +import { readJson, Tree } from '@nx/devkit'; +import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing'; +import { vueInitGenerator } from './init'; +import { InitSchema } from './schema'; + +// TODO: more or different to be added here +describe('init', () => { + let tree: Tree; + let schema: InitSchema = { + skipFormat: false, + }; + + beforeEach(() => { + tree = createTreeWithEmptyWorkspace(); + }); + + it('should add react dependencies', async () => { + await vueInitGenerator(tree, schema); + const packageJson = readJson(tree, 'package.json'); + expect(packageJson.dependencies['vue']).toBeDefined(); + }); + + it('should not add jest config if unitTestRunner is none', async () => { + await vueInitGenerator(tree, { ...schema, unitTestRunner: 'none' }); + expect(tree.exists('jest.config.js')).toEqual(false); + }); +}); diff --git a/packages/vue/src/generators/init/init.ts b/packages/vue/src/generators/init/init.ts new file mode 100755 index 00000000000000..9f936609a11a37 --- /dev/null +++ b/packages/vue/src/generators/init/init.ts @@ -0,0 +1,70 @@ +import { + addDependenciesToPackageJson, + convertNxGenerator, + GeneratorCallback, + readNxJson, + removeDependenciesFromPackageJson, + runTasksInSerial, + Tree, + updateNxJson, +} from '@nx/devkit'; + +import { initGenerator as jsInitGenerator } from '@nx/js'; +import { nxVersion, vueVersion } from '../../utils/versions'; +import { InitSchema } from './schema'; + +function setDefault(host: Tree) { + const workspace = readNxJson(host); + + workspace.generators = workspace.generators || {}; + const vueGenerators = workspace.generators['@nx/vue'] || {}; + const generators = { + ...workspace.generators, + '@nx/vue': { + ...vueGenerators, + application: { + ...vueGenerators.application, + babel: true, + }, + }, + }; + + updateNxJson(host, { ...workspace, generators }); +} + +function updateDependencies(host: Tree, _schema: InitSchema) { + removeDependenciesFromPackageJson(host, ['@nx/vue'], []); + + const dependencies = { + vue: vueVersion, + }; + + return addDependenciesToPackageJson(host, dependencies, { + '@nx/vue': nxVersion, + }); +} + +export async function vueInitGenerator(host: Tree, schema: InitSchema) { + const tasks: GeneratorCallback[] = []; + + const jsInitTask = await jsInitGenerator(host, { + ...schema, + tsConfigName: schema.rootProject ? 'tsconfig.json' : 'tsconfig.base.json', + skipFormat: true, + }); + + tasks.push(jsInitTask); + + setDefault(host); + + if (!schema.skipPackageJson) { + const installTask = updateDependencies(host, schema); + tasks.push(installTask); + } + + return runTasksInSerial(...tasks); +} + +export default vueInitGenerator; + +export const vueInitSchematic = convertNxGenerator(vueInitGenerator); diff --git a/packages/vue/src/generators/init/schema.d.ts b/packages/vue/src/generators/init/schema.d.ts new file mode 100644 index 00000000000000..fd2e1db972b4ff --- /dev/null +++ b/packages/vue/src/generators/init/schema.d.ts @@ -0,0 +1,9 @@ +export interface InitSchema { + unitTestRunner?: 'vitest' | 'none'; // TODO: more or different to be added here + e2eTestRunner?: 'cypress' | 'playwright' | 'none'; // TODO: more or different to be added here + skipFormat?: boolean; + skipPackageJson?: boolean; + js?: boolean; + rootProject?: boolean; + // TODO: more or different to be added here +} diff --git a/packages/vue/src/generators/init/schema.json b/packages/vue/src/generators/init/schema.json new file mode 100644 index 00000000000000..4502f0ef3c08b7 --- /dev/null +++ b/packages/vue/src/generators/init/schema.json @@ -0,0 +1,43 @@ +{ + "$schema": "http://json-schema.org/schema", + "$id": "NxVueInit", + "title": "Init Vue Plugin", + "description": "Initialize a Vue Plugin.", + "cli": "nx", + "type": "object", + "properties": { + "unitTestRunner": { + "description": "Adds the specified unit test runner.", + "type": "string", + "enum": ["vitest", "none"], + "default": "vitest" + }, + "e2eTestRunner": { + "description": "Adds the specified E2E test runner.", + "type": "string", + "enum": ["cypress", "playwright", "none"], + "default": "cypress" + }, + "skipFormat": { + "description": "Skip formatting files.", + "type": "boolean", + "default": false + }, + "skipPackageJson": { + "description": "Do not add dependencies to `package.json`.", + "type": "boolean", + "default": false + }, + "js": { + "type": "boolean", + "description": "Use JavaScript instead of TypeScript", + "default": false + }, + "rootProject": { + "description": "Create a project at the root of the workspace", + "type": "boolean", + "default": false + } + }, + "required": [] +} diff --git a/packages/vue/src/generators/library/files/README.md b/packages/vue/src/generators/library/files/README.md new file mode 100644 index 00000000000000..8c7900842716ee --- /dev/null +++ b/packages/vue/src/generators/library/files/README.md @@ -0,0 +1,7 @@ +# <%= name %> + +This library was generated with [Nx](https://nx.dev). + +## Running unit tests + +Run `nx test <%= name %>` to execute the unit tests via [Vitest](https://vitest.dev/). diff --git a/packages/vue/src/generators/library/files/package.json__tmpl__ b/packages/vue/src/generators/library/files/package.json__tmpl__ new file mode 100644 index 00000000000000..507420ee308347 --- /dev/null +++ b/packages/vue/src/generators/library/files/package.json__tmpl__ @@ -0,0 +1,12 @@ +{ + "name": "<%= name %>", + "version": "0.0.1", + "main": "./index.js", + "types": "./index.d.ts", + "exports": { + ".": { + "import": "./index.mjs", + "require": "./index.js" + } + } +} diff --git a/packages/vue/src/generators/library/files/src/index.ts__tmpl__ b/packages/vue/src/generators/library/files/src/index.ts__tmpl__ new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/packages/vue/src/generators/library/files/tsconfig.lib.json__tmpl__ b/packages/vue/src/generators/library/files/tsconfig.lib.json__tmpl__ new file mode 100644 index 00000000000000..9cfc471922ad4e --- /dev/null +++ b/packages/vue/src/generators/library/files/tsconfig.lib.json__tmpl__ @@ -0,0 +1,23 @@ +{ + "extends": "@vue/tsconfig/tsconfig.dom.json", + "compilerOptions": { + "outDir": "<%= offsetFromRoot %>dist/out-tsc", + "composite": true, + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + }, + "types": ["node"] + }, + "exclude": [ + "src/**/__tests__/*", + "**/*.spec.ts", + "**/*.test.ts", + "**/*.spec.tsx", + "**/*.test.tsx", + "**/*.spec.js", + "**/*.test.js", + "**/*.spec.jsx", + "**/*.test.jsx"], + "include": ["env.d.ts", "src/**/*", "src/**/*.vue"] +} diff --git a/packages/vue/src/generators/library/files/tsconfig.node.json__tmpl__ b/packages/vue/src/generators/library/files/tsconfig.node.json__tmpl__ new file mode 100644 index 00000000000000..dee96bed470be6 --- /dev/null +++ b/packages/vue/src/generators/library/files/tsconfig.node.json__tmpl__ @@ -0,0 +1,16 @@ +{ + "extends": "@tsconfig/node18/tsconfig.json", + "include": [ + "vite.config.*", + "vitest.config.*", + "cypress.config.*", + "nightwatch.conf.*", + "playwright.config.*" + ], + "compilerOptions": { + "composite": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "types": ["node"] + } +} diff --git a/packages/vue/src/generators/library/files/tsconfig.vitest.json__tmpl__ b/packages/vue/src/generators/library/files/tsconfig.vitest.json__tmpl__ new file mode 100644 index 00000000000000..80be606c41b0fc --- /dev/null +++ b/packages/vue/src/generators/library/files/tsconfig.vitest.json__tmpl__ @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.lib.json", + "exclude": [], + "compilerOptions": { + "composite": true, + "lib": [], + "types": ["node", "jsdom"] + } +} diff --git a/packages/vue/src/generators/library/lib/.gitkeep b/packages/vue/src/generators/library/lib/.gitkeep new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/packages/vue/src/generators/library/lib/add-linting.ts b/packages/vue/src/generators/library/lib/add-linting.ts new file mode 100644 index 00000000000000..79cabba02ec39b --- /dev/null +++ b/packages/vue/src/generators/library/lib/add-linting.ts @@ -0,0 +1,45 @@ +import { Tree } from 'nx/src/generators/tree'; +import { Linter, lintProjectGenerator } from '@nx/linter'; +import { joinPathFragments } from 'nx/src/utils/path'; +import { addDependenciesToPackageJson, runTasksInSerial } from '@nx/devkit'; + +import { NormalizedSchema } from '../schema'; +import { extraEslintDependencies } from '../../../utils/lint'; +import { + addExtendsToLintConfig, + isEslintConfigSupported, +} from '@nx/linter/src/generators/utils/eslint-file'; + +export async function addLinting(host: Tree, options: NormalizedSchema) { + if (options.linter === Linter.EsLint) { + const lintTask = await lintProjectGenerator(host, { + linter: options.linter, + project: options.name, + tsConfigPaths: [ + joinPathFragments(options.projectRoot, 'tsconfig.lib.json'), + ], + unitTestRunner: options.unitTestRunner, + eslintFilePatterns: [`${options.projectRoot}/**/*.{ts,tsx,js,jsx}`], + skipFormat: true, + skipPackageJson: options.skipPackageJson, + setParserOptionsProject: options.setParserOptionsProject, + }); + + if (isEslintConfigSupported(host)) { + addExtendsToLintConfig(host, options.projectRoot, 'plugin:@nx/vue'); + } + + let installTask = () => {}; + if (!options.skipPackageJson) { + installTask = await addDependenciesToPackageJson( + host, + extraEslintDependencies.dependencies, + extraEslintDependencies.devDependencies + ); + } + + return runTasksInSerial(lintTask, installTask); + } else { + return () => {}; + } +} diff --git a/packages/vue/src/generators/library/lib/create-files.ts b/packages/vue/src/generators/library/lib/create-files.ts new file mode 100644 index 00000000000000..276481771e2e6a --- /dev/null +++ b/packages/vue/src/generators/library/lib/create-files.ts @@ -0,0 +1,49 @@ +import type { Tree } from '@nx/devkit'; +import { + generateFiles, + joinPathFragments, + names, + offsetFromRoot, + toJS, + writeJson, +} from '@nx/devkit'; +import { getRelativePathToRootTsConfig } from '@nx/js'; +import { NormalizedSchema } from '../schema'; +import { createTsConfig } from '../../../utils/create-ts-config'; + +export function createFiles(host: Tree, options: NormalizedSchema) { + const relativePathToRootTsConfig = getRelativePathToRootTsConfig( + host, + options.projectRoot + ); + const substitutions = { + ...options, + ...names(options.name), + tmpl: '', + offsetFromRoot: offsetFromRoot(options.projectRoot), + fileName: options.fileName, + }; + + generateFiles( + host, + joinPathFragments(__dirname, '../files'), + options.projectRoot, + substitutions + ); + + if (!options.publishable && !options.buildable) { + host.delete(`${options.projectRoot}/package.json`); + } + + if (options.js) { + toJS(host); + } + + createTsConfig( + host, + options.projectRoot, + 'lib', + options, + relativePathToRootTsConfig + ); +} diff --git a/packages/vue/src/generators/library/lib/normalize-options.spec.ts b/packages/vue/src/generators/library/lib/normalize-options.spec.ts new file mode 100644 index 00000000000000..d3477e24782e1d --- /dev/null +++ b/packages/vue/src/generators/library/lib/normalize-options.spec.ts @@ -0,0 +1,103 @@ +import type { Tree } from '@nx/devkit'; +import { Linter } from '@nx/linter'; +import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing'; +import { normalizeOptions } from './normalize-options'; + +describe('normalizeOptions', () => { + let tree: Tree; + + beforeEach(() => { + tree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' }); + }); + + it('should set unitTestRunner=jest and bundler=none by default', async () => { + const options = await normalizeOptions(tree, { + name: 'test', + linter: Linter.None, + unitTestRunner: 'vitest', + }); + + expect(options).toMatchObject({ + buildable: false, + bundler: 'none', + compiler: 'babel', + unitTestRunner: 'vitest', + }); + }); + + it('should set buildable to true when bundler is not "none"', async () => { + const options = await normalizeOptions(tree, { + name: 'test', + linter: Linter.None, + bundler: 'vite', + }); + + expect(options).toMatchObject({ + buildable: true, + bundler: 'vite', + }); + }); + + it('should set unitTestRunner=vitest by default when bundler is vite', async () => { + const options = await normalizeOptions(tree, { + name: 'test', + linter: Linter.None, + bundler: 'vite', + unitTestRunner: 'vitest', + }); + + expect(options).toMatchObject({ + buildable: true, + bundler: 'vite', + compiler: 'babel', + unitTestRunner: 'vitest', + }); + }); + + it('should set maintain unitTestRunner when bundler is vite', async () => { + const options = await normalizeOptions(tree, { + name: 'test', + linter: Linter.None, + bundler: 'vite', + unitTestRunner: 'vitest', + }); + + expect(options).toMatchObject({ + buildable: true, + bundler: 'vite', + compiler: 'babel', + unitTestRunner: 'vitest', + }); + }); + + it('should set bundler to rollup if buildable is true not no bundler is passed', async () => { + const options = await normalizeOptions(tree, { + name: 'test', + linter: Linter.None, + buildable: true, + unitTestRunner: 'vitest', + }); + + expect(options).toMatchObject({ + buildable: true, + bundler: 'vite', + unitTestRunner: 'vitest', + }); + }); + + it('should set bundler to rollup if buildable is true and bundler is none ', async () => { + const options = await normalizeOptions(tree, { + name: 'test', + linter: Linter.None, + buildable: true, + bundler: 'none', + unitTestRunner: 'vitest', + }); + + expect(options).toMatchObject({ + buildable: true, + bundler: 'vite', + unitTestRunner: 'vitest', + }); + }); +}); diff --git a/packages/vue/src/generators/library/lib/normalize-options.ts b/packages/vue/src/generators/library/lib/normalize-options.ts new file mode 100644 index 00000000000000..4e2e8fd30d94bd --- /dev/null +++ b/packages/vue/src/generators/library/lib/normalize-options.ts @@ -0,0 +1,86 @@ +import { getProjects, logger, normalizePath, Tree } from '@nx/devkit'; +import { determineProjectNameAndRootOptions } from '@nx/devkit/src/generators/project-name-and-root-utils'; +import { NormalizedSchema, Schema } from '../schema'; + +export async function normalizeOptions( + host: Tree, + options: Schema +): Promise { + const { + projectName, + names: projectNames, + projectRoot, + importPath, + } = await determineProjectNameAndRootOptions(host, { + name: options.name, + projectType: 'library', + directory: options.directory, + importPath: options.importPath, + projectNameAndRootFormat: options.projectNameAndRootFormat, + callingGenerator: '@nx/vue:library', + }); + + const fileName = options.simpleName + ? projectNames.projectSimpleName + : projectNames.projectFileName; + + const parsedTags = options.tags + ? options.tags.split(',').map((s) => s.trim()) + : []; + + let bundler = options.bundler ?? 'none'; + + if (bundler === 'none') { + if (options.publishable) { + logger.warn( + `Publishable libraries cannot be used with bundler: 'none'. Defaulting to 'rollup'.` + ); + bundler = 'vite'; + } + if (options.buildable) { + logger.warn( + `Buildable libraries cannot be used with bundler: 'none'. Defaulting to 'rollup'.` + ); + bundler = 'vite'; + } + } + + const normalized = { + ...options, + bundler, + fileName, + routePath: `/${projectNames.projectSimpleName}`, + name: projectName, + projectRoot, + parsedTags, + importPath, + } as NormalizedSchema; + + // Libraries with a bundler or is publishable must also be buildable. + normalized.buildable = Boolean( + normalized.bundler !== 'none' || options.buildable || options.publishable + ); + + normalized.inSourceTests === normalized.minimal || normalized.inSourceTests; + + if (options.appProject) { + const appProjectConfig = getProjects(host).get(options.appProject); + + if (appProjectConfig.projectType !== 'application') { + throw new Error( + `appProject expected type of "application" but got "${appProjectConfig.projectType}"` + ); + } + + try { + normalized.appMain = appProjectConfig.targets.build.options.main; + normalized.appSourceRoot = normalizePath(appProjectConfig.sourceRoot); + } catch (e) { + throw new Error( + `Could not locate project main for ${options.appProject}` + ); + } + } + + return normalized; +} diff --git a/packages/vue/src/generators/library/library.spec.ts b/packages/vue/src/generators/library/library.spec.ts new file mode 100644 index 00000000000000..ebc8bfd12427f7 --- /dev/null +++ b/packages/vue/src/generators/library/library.spec.ts @@ -0,0 +1,818 @@ +import { installedCypressVersion } from '@nx/cypress/src/utils/cypress-version'; +import { + getProjects, + readJson, + readProjectConfiguration, + Tree, + updateJson, +} from '@nx/devkit'; +import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing'; +import { Linter } from '@nx/linter'; +import { nxVersion } from '../../utils/versions'; +import applicationGenerator from '../application/application'; +import libraryGenerator from './library'; +import { Schema } from './schema'; +// need to mock cypress otherwise it'll use the nx installed version from package.json +// which is v9 while we are testing for the new v10 version +jest.mock('@nx/cypress/src/utils/cypress-version'); +describe('lib', () => { + let tree: Tree; + let mockedInstalledCypressVersion: jest.Mock< + ReturnType + > = installedCypressVersion as never; + let defaultSchema: Schema = { + name: 'myLib', + linter: Linter.EsLint, + skipFormat: false, + skipTsConfig: false, + unitTestRunner: 'jest', + style: 'css', + component: true, + strict: true, + simpleName: false, + }; + + beforeEach(() => { + mockedInstalledCypressVersion.mockReturnValue(10); + tree = createTreeWithEmptyWorkspace(); + updateJson(tree, '/package.json', (json) => { + json.devDependencies = { + '@nx/cypress': nxVersion, + '@nx/jest': nxVersion, + '@nx/rollup': nxVersion, + '@nx/vite': nxVersion, + '@nx/webpack': nxVersion, + }; + return json; + }); + }); + + it('should update project configuration', async () => { + await libraryGenerator(tree, defaultSchema); + const project = readProjectConfiguration(tree, 'my-lib'); + expect(project.root).toEqual('my-lib'); + expect(project.targets.build).toBeUndefined(); + expect(project.targets.lint).toEqual({ + executor: '@nx/linter:eslint', + outputs: ['{options.outputFile}'], + options: { + lintFilePatterns: ['my-lib/**/*.{ts,tsx,js,jsx}'], + }, + }); + }); + + it('should add vite types to tsconfigs', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + bundler: 'vite', + unitTestRunner: 'vitest', + }); + const tsconfigApp = readJson(tree, 'my-lib/tsconfig.lib.json'); + expect(tsconfigApp.compilerOptions.types).toEqual([ + 'node', + '@nx/react/typings/cssmodule.d.ts', + '@nx/react/typings/image.d.ts', + 'vite/client', + ]); + const tsconfigSpec = readJson(tree, 'my-lib/tsconfig.spec.json'); + expect(tsconfigSpec.compilerOptions.types).toEqual([ + 'vitest/globals', + 'vitest/importMeta', + 'vite/client', + 'node', + ]); + }); + + it('should update tags', async () => { + await libraryGenerator(tree, { ...defaultSchema, tags: 'one,two' }); + const project = readProjectConfiguration(tree, 'my-lib'); + expect(project).toEqual( + expect.objectContaining({ + tags: ['one', 'two'], + }) + ); + }); + + it('should add react and react-dom packages to package.json if not already present', async () => { + await libraryGenerator(tree, defaultSchema); + + const packageJson = readJson(tree, '/package.json'); + + expect(packageJson).toMatchObject({ + dependencies: { + react: expect.anything(), + 'react-dom': expect.anything(), + }, + }); + }); + + it('should update root tsconfig.base.json', async () => { + await libraryGenerator(tree, defaultSchema); + const tsconfigJson = readJson(tree, '/tsconfig.base.json'); + expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ + 'my-lib/src/index.ts', + ]); + }); + + it('should create tsconfig.base.json out of tsconfig.json', async () => { + tree.rename('tsconfig.base.json', 'tsconfig.json'); + + await libraryGenerator(tree, defaultSchema); + + expect(tree.exists('tsconfig.base.json')).toEqual(true); + const tsconfigJson = readJson(tree, 'tsconfig.base.json'); + expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ + 'my-lib/src/index.ts', + ]); + }); + + it('should update root tsconfig.base.json (no existing path mappings)', async () => { + updateJson(tree, 'tsconfig.base.json', (json) => { + json.compilerOptions.paths = undefined; + return json; + }); + + await libraryGenerator(tree, defaultSchema); + const tsconfigJson = readJson(tree, '/tsconfig.base.json'); + expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ + 'my-lib/src/index.ts', + ]); + }); + + it('should create a local tsconfig.json', async () => { + await libraryGenerator(tree, defaultSchema); + + const tsconfigJson = readJson(tree, 'my-lib/tsconfig.json'); + expect(tsconfigJson.extends).toBe('../tsconfig.base.json'); + expect(tsconfigJson.references).toEqual([ + { + path: './tsconfig.lib.json', + }, + { + path: './tsconfig.spec.json', + }, + ]); + expect(tsconfigJson.compilerOptions.strict).toEqual(true); + }); + + it('should extend the local tsconfig.json with tsconfig.spec.json', async () => { + await libraryGenerator(tree, defaultSchema); + const tsconfigJson = readJson(tree, 'my-lib/tsconfig.spec.json'); + expect(tsconfigJson.extends).toEqual('./tsconfig.json'); + }); + + it('should extend the local tsconfig.json with tsconfig.lib.json', async () => { + await libraryGenerator(tree, defaultSchema); + const tsconfigJson = readJson(tree, 'my-lib/tsconfig.lib.json'); + expect(tsconfigJson.extends).toEqual('./tsconfig.json'); + }); + + it('should ignore test files in tsconfig.lib.json', async () => { + await libraryGenerator(tree, defaultSchema); + const tsconfigJson = readJson(tree, 'my-lib/tsconfig.lib.json'); + expect(tsconfigJson.exclude).toEqual([ + 'jest.config.ts', + 'src/**/*.spec.ts', + 'src/**/*.test.ts', + 'src/**/*.spec.tsx', + 'src/**/*.test.tsx', + 'src/**/*.spec.js', + 'src/**/*.test.js', + 'src/**/*.spec.jsx', + 'src/**/*.test.jsx', + ]); + }); + + it('should generate files', async () => { + await libraryGenerator(tree, defaultSchema); + expect(tree.exists('my-lib/package.json')).toBeFalsy(); + expect(tree.exists(`my-lib/jest.config.ts`)).toBeTruthy(); + expect(tree.exists('my-lib/src/index.ts')).toBeTruthy(); + expect(tree.exists('my-lib/src/lib/my-lib.tsx')).toBeTruthy(); + expect(tree.exists('my-lib/src/lib/my-lib.module.css')).toBeTruthy(); + expect(tree.exists('my-lib/src/lib/my-lib.spec.tsx')).toBeTruthy(); + + const eslintJson = readJson(tree, 'my-lib/.eslintrc.json'); + expect(eslintJson).toMatchInlineSnapshot(` + { + "extends": [ + "plugin:@nx/react", + "../.eslintrc.json", + ], + "ignorePatterns": [ + "!**/*", + ], + "overrides": [ + { + "files": [ + "*.ts", + "*.tsx", + "*.js", + "*.jsx", + ], + "rules": {}, + }, + { + "files": [ + "*.ts", + "*.tsx", + ], + "rules": {}, + }, + { + "files": [ + "*.js", + "*.jsx", + ], + "rules": {}, + }, + ], + } + `); + }); + it('should update jest.config.ts for babel', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + buildable: true, + compiler: 'babel', + }); + expect(tree.read('my-lib/jest.config.ts', 'utf-8')).toContain( + "['babel-jest', { presets: ['@nx/react/babel'] }]" + ); + }); + + it('should add @babel/preset-react when using babel compiler', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + compiler: 'babel', + directory: 'myDir', + tags: 'one', + }); + + const packageJson = readJson(tree, 'package.json'); + expect(packageJson.devDependencies['@babel/preset-react']).toBeDefined(); + }); + + describe('nested', () => { + it('should update tags and implicitDependencies', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + directory: 'myDir', + tags: 'one', + }); + const myLib = readProjectConfiguration(tree, 'my-dir-my-lib'); + expect(myLib).toEqual( + expect.objectContaining({ + tags: ['one'], + }) + ); + + await libraryGenerator(tree, { + ...defaultSchema, + name: 'myLib2', + directory: 'myDir', + tags: 'one,two', + }); + + const myLib2 = readProjectConfiguration(tree, 'my-dir-my-lib2'); + expect(myLib2).toEqual( + expect.objectContaining({ + tags: ['one', 'two'], + }) + ); + }); + + it('should generate files', async () => { + await libraryGenerator(tree, { ...defaultSchema, directory: 'myDir' }); + expect(tree.exists(`my-dir/my-lib/jest.config.ts`)).toBeTruthy(); + expect(tree.exists('my-dir/my-lib/src/index.ts')).toBeTruthy(); + expect( + tree.exists('my-dir/my-lib/src/lib/my-dir-my-lib.tsx') + ).toBeTruthy(); + expect( + tree.exists('my-dir/my-lib/src/lib/my-dir-my-lib.module.css') + ).toBeTruthy(); + expect( + tree.exists('my-dir/my-lib/src/lib/my-dir-my-lib.spec.tsx') + ).toBeTruthy(); + }); + + it('should update jest.config.ts for babel', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + directory: 'myDir', + buildable: true, + compiler: 'babel', + }); + expect(tree.read('my-dir/my-lib/jest.config.ts', 'utf-8')).toContain( + "['babel-jest', { presets: ['@nx/react/babel'] }]" + ); + }); + + it('should update project configurations', async () => { + await libraryGenerator(tree, { ...defaultSchema, directory: 'myDir' }); + const config = readProjectConfiguration(tree, 'my-dir-my-lib'); + + expect(config.root).toEqual('my-dir/my-lib'); + expect(config.targets.lint).toEqual({ + executor: '@nx/linter:eslint', + outputs: ['{options.outputFile}'], + options: { + lintFilePatterns: ['my-dir/my-lib/**/*.{ts,tsx,js,jsx}'], + }, + }); + }); + + it('should update root tsconfig.base.json', async () => { + await libraryGenerator(tree, { ...defaultSchema, directory: 'myDir' }); + const tsconfigJson = readJson(tree, '/tsconfig.base.json'); + expect(tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']).toEqual( + ['my-dir/my-lib/src/index.ts'] + ); + expect( + tsconfigJson.compilerOptions.paths['my-dir-my-lib/*'] + ).toBeUndefined(); + }); + + it('should create a local tsconfig.json', async () => { + await libraryGenerator(tree, { ...defaultSchema, directory: 'myDir' }); + + const tsconfigJson = readJson(tree, 'my-dir/my-lib/tsconfig.json'); + expect(tsconfigJson.extends).toBe('../../tsconfig.base.json'); + expect(tsconfigJson.references).toEqual([ + { + path: './tsconfig.lib.json', + }, + { + path: './tsconfig.spec.json', + }, + ]); + }); + }); + + describe('--style scss', () => { + it('should use scss for styles', async () => { + await libraryGenerator(tree, { ...defaultSchema, style: 'scss' }); + + expect(tree.exists('my-lib/src/lib/my-lib.module.scss')).toBeTruthy(); + }); + }); + + describe('--style none', () => { + it('should not use styles when style none', async () => { + await libraryGenerator(tree, { ...defaultSchema, style: 'none' }); + + expect(tree.exists('my-lib/src/lib/my-lib.tsx')).toBeTruthy(); + expect(tree.exists('my-lib/src/lib/my-lib.spec.tsx')).toBeTruthy(); + expect(tree.exists('my-lib/src/lib/my-lib.css')).toBeFalsy(); + expect(tree.exists('my-lib/src/lib/my-lib.scss')).toBeFalsy(); + expect(tree.exists('my-lib/src/lib/my-lib.styl')).toBeFalsy(); + expect(tree.exists('my-lib/src/lib/my-lib.module.css')).toBeFalsy(); + expect(tree.exists('my-lib/src/lib/my-lib.module.scss')).toBeFalsy(); + expect(tree.exists('my-lib/src/lib/my-lib.module.styl')).toBeFalsy(); + + const content = tree.read('my-lib/src/lib/my-lib.tsx', 'utf-8'); + expect(content).not.toContain('styled-components'); + expect(content).not.toContain(''); + expect(content).not.toContain('@emotion/styled'); + expect(content).not.toContain(''); + + //for imports + expect(content).not.toContain('app.styl'); + expect(content).not.toContain('app.css'); + expect(content).not.toContain('app.scss'); + expect(content).not.toContain('app.module.styl'); + expect(content).not.toContain('app.module.css'); + expect(content).not.toContain('app.module.scss'); + }); + }); + + describe('--no-component', () => { + it('should not generate components or styles', async () => { + await libraryGenerator(tree, { ...defaultSchema, component: false }); + + expect(tree.exists('my-lib/src/lib')).toBeFalsy(); + }); + }); + + describe('--globalCss', () => { + it('should not generate .module styles', async () => { + await libraryGenerator(tree, { ...defaultSchema, globalCss: true }); + + expect(tree.exists('my-lib/src/lib/my-lib.css')); + expect(tree.exists('my-lib/src/lib/my-lib.module.css')).toBeFalsy(); + }); + }); + + describe('--unit-test-runner none', () => { + it('should not generate test configuration', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + unitTestRunner: 'none', + }); + + expect(tree.exists('my-lib/tsconfig.spec.json')).toBeFalsy(); + expect(tree.exists('my-lib/jest.config.ts')).toBeFalsy(); + const config = readProjectConfiguration(tree, 'my-lib'); + expect(config.targets.test).toBeUndefined(); + expect(config.targets.lint).toMatchInlineSnapshot(` + { + "executor": "@nx/linter:eslint", + "options": { + "lintFilePatterns": [ + "my-lib/**/*.{ts,tsx,js,jsx}", + ], + }, + "outputs": [ + "{options.outputFile}", + ], + } + `); + }); + }); + + describe('--appProject', () => { + it('should add new route to existing routing code', async () => { + await applicationGenerator(tree, { + compiler: 'babel', + e2eTestRunner: 'none', + linter: Linter.EsLint, + skipFormat: true, + unitTestRunner: 'jest', + name: 'myApp', + routing: true, + style: 'css', + bundler: 'webpack', + projectNameAndRootFormat: 'as-provided', + }); + + await libraryGenerator(tree, { + ...defaultSchema, + appProject: 'my-app', + projectNameAndRootFormat: 'as-provided', + }); + + const appSource = tree.read('my-app/src/app/app.tsx', 'utf-8'); + const mainSource = tree.read('my-app/src/main.tsx', 'utf-8'); + + expect(mainSource).toContain('react-router-dom'); + expect(mainSource).toContain(''); + expect(appSource).toContain('@proj/my-lib'); + expect(appSource).toContain('react-router-dom'); + expect(appSource).toMatch(/ { + await applicationGenerator(tree, { + e2eTestRunner: 'none', + linter: Linter.EsLint, + skipFormat: true, + unitTestRunner: 'jest', + name: 'myApp', + style: 'css', + bundler: 'webpack', + projectNameAndRootFormat: 'as-provided', + }); + + await libraryGenerator(tree, { + ...defaultSchema, + appProject: 'my-app', + projectNameAndRootFormat: 'as-provided', + }); + + const appSource = tree.read('my-app/src/app/app.tsx', 'utf-8'); + const mainSource = tree.read('my-app/src/main.tsx', 'utf-8'); + + expect(mainSource).toContain('react-router-dom'); + expect(mainSource).toContain(''); + expect(appSource).toContain('@proj/my-lib'); + expect(appSource).toContain('react-router-dom'); + expect(appSource).toMatch(/ { + it('should have a builder defined', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + buildable: true, + }); + + const projectsConfigurations = getProjects(tree); + + expect(projectsConfigurations.get('my-lib').targets.build).toBeDefined(); + }); + }); + + describe('--publishable', () => { + it('should add build targets', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + publishable: true, + importPath: '@proj/my-lib', + }); + + const projectsConfigurations = getProjects(tree); + + expect(projectsConfigurations.get('my-lib').targets.build).toMatchObject({ + executor: '@nx/rollup:rollup', + outputs: ['{options.outputPath}'], + options: { + external: ['react', 'react-dom', 'react/jsx-runtime'], + entryFile: 'my-lib/src/index.ts', + outputPath: 'dist/my-lib', + project: 'my-lib/package.json', + tsConfig: 'my-lib/tsconfig.lib.json', + rollupConfig: '@nx/react/plugins/bundle-rollup', + }, + }); + }); + + it('should fail if no importPath is provided with publishable', async () => { + expect.assertions(1); + + try { + await libraryGenerator(tree, { + ...defaultSchema, + directory: 'myDir', + publishable: true, + }); + } catch (e) { + expect(e.message).toContain( + 'For publishable libs you have to provide a proper "--importPath" which needs to be a valid npm package name (e.g. my-awesome-lib or @myorg/my-lib)' + ); + } + }); + + it('should support styled-components', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + publishable: true, + importPath: '@proj/my-lib', + style: 'styled-components', + }); + + const config = readProjectConfiguration(tree, 'my-lib'); + const babelrc = readJson(tree, 'my-lib/.babelrc'); + + expect(config.targets.build).toMatchObject({ + options: { + external: ['react', 'react-dom', 'react/jsx-runtime'], + }, + }); + expect(babelrc.plugins).toEqual([ + ['styled-components', { pure: true, ssr: true }], + ]); + }); + + it('should support @emotion/styled', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + publishable: true, + importPath: '@proj/my-lib', + style: '@emotion/styled', + }); + + const config = readProjectConfiguration(tree, 'my-lib'); + const babelrc = readJson(tree, 'my-lib/.babelrc'); + const tsconfigJson = readJson(tree, 'my-lib/tsconfig.json'); + + expect(config.targets.build).toMatchObject({ + options: { + external: ['react', 'react-dom', '@emotion/react/jsx-runtime'], + }, + }); + expect(babelrc.plugins).toEqual(['@emotion/babel-plugin']); + expect(tsconfigJson.compilerOptions['jsxImportSource']).toEqual( + '@emotion/react' + ); + }); + + it('should support styled-jsx', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + publishable: true, + importPath: '@proj/my-lib', + style: 'styled-jsx', + }); + + const config = readProjectConfiguration(tree, 'my-lib'); + const babelrc = readJson(tree, 'my-lib/.babelrc'); + + expect(config.targets.build).toMatchObject({ + options: { + external: ['react', 'react-dom', 'react/jsx-runtime'], + }, + }); + expect(babelrc.plugins).toEqual(['styled-jsx/babel']); + }); + + it('should support style none', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + publishable: true, + importPath: '@proj/my-lib', + style: 'none', + }); + + const config = readProjectConfiguration(tree, 'my-lib'); + + expect(config.targets.build).toMatchObject({ + options: { + external: ['react', 'react-dom', 'react/jsx-runtime'], + }, + }); + }); + + it('should add package.json and .babelrc', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + publishable: true, + importPath: '@proj/my-lib', + }); + + const packageJson = readJson(tree, '/my-lib/package.json'); + expect(packageJson.name).toEqual('@proj/my-lib'); + expect(tree.exists('/my-lib/.babelrc')); + }); + }); + + describe('--js', () => { + it('should generate JS files', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + js: true, + }); + + expect(tree.exists('/my-lib/src/index.js')).toBe(true); + }); + }); + + describe('--importPath', () => { + it('should update the package.json & tsconfig with the given import path', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + publishable: true, + directory: 'myDir', + importPath: '@myorg/lib', + }); + const packageJson = readJson(tree, 'my-dir/my-lib/package.json'); + const tsconfigJson = readJson(tree, '/tsconfig.base.json'); + + expect(packageJson.name).toBe('@myorg/lib'); + expect( + tsconfigJson.compilerOptions.paths[packageJson.name] + ).toBeDefined(); + }); + + it('should fail if the same importPath has already been used', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + name: 'myLib1', + publishable: true, + importPath: '@myorg/lib', + }); + + try { + await libraryGenerator(tree, { + ...defaultSchema, + name: 'myLib2', + publishable: true, + importPath: '@myorg/lib', + }); + } catch (e) { + expect(e.message).toContain( + 'You already have a library using the import path' + ); + } + + expect.assertions(1); + }); + }); + + describe('--no-strict', () => { + it('should not add options for strict mode', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + strict: false, + }); + const tsconfigJson = readJson(tree, '/my-lib/tsconfig.json'); + + expect(tsconfigJson.compilerOptions.strict).toEqual(false); + }); + }); + + describe('--compiler', () => { + it('should install swc dependencies if needed', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + buildable: true, + compiler: 'swc', + }); + const packageJson = readJson(tree, 'package.json'); + + expect(packageJson.devDependencies['@swc/core']).toEqual( + expect.any(String) + ); + }); + }); + + describe('--skipPackageJson', () => { + it('should not add dependencies to package.json when true', async () => { + // ARRANGE + const packageJsonBeforeGenerator = tree.read('package.json', 'utf-8'); + // ACT + await libraryGenerator(tree, { + ...defaultSchema, + skipPackageJson: true, + }); + + // ASSERT + expect(tree.read('package.json', 'utf-8')).toEqual( + packageJsonBeforeGenerator + ); + }); + }); + + describe('--setParserOptionsProject', () => { + it('should set the parserOptions.project in the eslintrc.json file', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + setParserOptionsProject: true, + }); + + const eslintConfig = readJson(tree, 'my-lib/.eslintrc.json'); + + expect(eslintConfig.overrides[0].parserOptions.project).toEqual([ + 'my-lib/tsconfig.*?.json', + ]); + }); + }); + + describe('--simpleName', () => { + it('should generate a library with a simple name', async () => { + await libraryGenerator(tree, { + ...defaultSchema, + simpleName: true, + directory: 'myDir', + }); + + const indexFile = tree.read('my-dir/my-lib/src/index.ts', 'utf-8'); + + expect(indexFile).toContain(`export * from './lib/my-lib';`); + + expect( + tree.exists('my-dir/my-lib/src/lib/my-lib.module.css') + ).toBeTruthy(); + + expect(tree.exists('my-dir/my-lib/src/lib/my-lib.spec.tsx')).toBeTruthy(); + + expect(tree.exists('my-dir/my-lib/src/lib/my-lib.tsx')).toBeTruthy(); + }); + }); + + it.each` + style + ${'styled-components'} + ${'styled-jsx'} + ${'@emotion/styled'} + `( + 'should generate valid .babelrc JSON config for CSS-in-JS solutions', + async ({ style }) => { + await libraryGenerator(tree, { + ...defaultSchema, + style, + compiler: 'babel', + name: 'myLib', + }); + + expect(() => { + readJson(tree, `my-lib/.babelrc`); + }).not.toThrow(); + } + ); + + it.each` + style | pkg + ${'less'} | ${'less'} + ${'scss'} | ${'sass'} + ${'styl'} | ${'stylus'} + `( + 'should add style preprocessor when vite is used', + async ({ style, pkg }) => { + await libraryGenerator(tree, { + ...defaultSchema, + style, + bundler: 'vite', + unitTestRunner: 'vitest', + name: 'myLib', + }); + + expect(readJson(tree, 'package.json')).toMatchObject({ + devDependencies: { + [pkg]: expect.any(String), + }, + }); + } + ); +}); diff --git a/packages/vue/src/generators/library/library.ts b/packages/vue/src/generators/library/library.ts new file mode 100644 index 00000000000000..1310b8747f77b5 --- /dev/null +++ b/packages/vue/src/generators/library/library.ts @@ -0,0 +1,150 @@ +import { + addProjectConfiguration, + convertNxGenerator, + ensurePackage, + formatFiles, + GeneratorCallback, + joinPathFragments, + runTasksInSerial, + Tree, + updateJson, +} from '@nx/devkit'; + +import { addTsConfigPath } from '@nx/js'; + +import { nxVersion } from '../../utils/versions'; +// import componentGenerator from '../component/component'; +import initGenerator from '../init/init'; +import { Schema } from './schema'; +import { normalizeOptions } from './lib/normalize-options'; +import { addLinting } from './lib/add-linting'; +import { createFiles } from './lib/create-files'; +import { extractTsConfigBase } from '../../utils/create-ts-config'; + +export async function libraryGenerator(host: Tree, schema: Schema) { + return await libraryGeneratorInternal(host, { + projectNameAndRootFormat: 'derived', + ...schema, + }); +} + +export async function libraryGeneratorInternal(host: Tree, schema: Schema) { + const tasks: GeneratorCallback[] = []; + + const options = await normalizeOptions(host, schema); + if (options.publishable === true && !schema.importPath) { + throw new Error( + `For publishable libs you have to provide a proper "--importPath" which needs to be a valid npm package name (e.g. my-awesome-lib or @myorg/my-lib)` + ); + } + + const initTask = await initGenerator(host, { + ...options, + e2eTestRunner: 'none', + skipFormat: true, + }); + tasks.push(initTask); + + addProjectConfiguration(host, options.name, { + root: options.projectRoot, + sourceRoot: joinPathFragments(options.projectRoot, 'src'), + projectType: 'library', + tags: options.parsedTags, + targets: {}, + }); + + const lintTask = await addLinting(host, options); + tasks.push(lintTask); + + createFiles(host, options); + + // Set up build target + if (options.buildable && options.bundler === 'vite') { + const { viteConfigurationGenerator } = ensurePackage< + typeof import('@nx/vite') + >('@nx/vite', nxVersion); + const viteTask = await viteConfigurationGenerator(host, { + uiFramework: 'react', + project: options.name, + newProject: true, + includeLib: true, + inSourceTests: options.inSourceTests, + includeVitest: options.unitTestRunner === 'vitest', + skipFormat: true, + testEnvironment: 'jsdom', + }); + tasks.push(viteTask); + } + + // Set up test target + if ( + options.unitTestRunner === 'vitest' && + options.bundler !== 'vite' // tests are already configured if bundler is vite + ) { + const { vitestGenerator } = ensurePackage( + '@nx/vite', + nxVersion + ); + const vitestTask = await vitestGenerator(host, { + uiFramework: 'react', + project: options.name, + coverageProvider: 'c8', + inSourceTests: options.inSourceTests, + skipFormat: true, + testEnvironment: 'jsdom', + }); + tasks.push(vitestTask); + } + + // TODO(katerina): Enable when component generator is ready + // if (options.component) { + // const componentTask = await componentGenerator(host, { + // name: options.fileName, + // project: options.name, + // flat: true, + // skipTests: + // options.unitTestRunner === 'none' || + // (options.unitTestRunner === 'vitest' && options.inSourceTests == true), + // export: true, + // routing: options.routing, + // js: options.js, + // pascalCaseFiles: options.pascalCaseFiles, + // inSourceTests: options.inSourceTests, + // skipFormat: true, + // }); + // tasks.push(componentTask); + // } + + if (options.publishable || options.buildable) { + updateJson(host, `${options.projectRoot}/package.json`, (json) => { + json.name = options.importPath; + return json; + }); + } + + // TODO(katerina): tbd + // const routeTask = updateAppRoutes(host, options); + // tasks.push(routeTask); + // setDefaults(host, options); + + extractTsConfigBase(host); + + if (!options.skipTsConfig) { + addTsConfigPath(host, options.importPath, [ + joinPathFragments( + options.projectRoot, + './src', + 'index.' + (options.js ? 'js' : 'ts') + ), + ]); + } + + if (!options.skipFormat) { + await formatFiles(host); + } + + return runTasksInSerial(...tasks); +} + +export default libraryGenerator; +export const librarySchematic = convertNxGenerator(libraryGenerator); diff --git a/packages/vue/src/generators/library/schema.d.ts b/packages/vue/src/generators/library/schema.d.ts new file mode 100644 index 00000000000000..40e3c69ace241f --- /dev/null +++ b/packages/vue/src/generators/library/schema.d.ts @@ -0,0 +1,41 @@ +import type { ProjectNameAndRootFormat } from '@nx/devkit/src/generators/project-name-and-root-utils'; +import type { Linter } from '@nx/linter'; +import type { SupportedStyles } from '../../../typings/style'; + +export interface Schema { + appProject?: string; + buildable?: boolean; + bundler?: 'none' | 'vite'; + component?: boolean; + directory?: string; + projectNameAndRootFormat?: ProjectNameAndRootFormat; + importPath?: string; + inSourceTests?: boolean; + js?: boolean; + linter: Linter; + name: string; + pascalCaseFiles?: boolean; + publishable?: boolean; + routing?: boolean; + setParserOptionsProject?: boolean; + skipFormat?: boolean; + skipPackageJson?: boolean; + skipTsConfig?: boolean; + strict?: boolean; + tags?: string; + unitTestRunner?: 'vitest' | 'none'; + minimal?: boolean; + simpleName?: boolean; +} + +export interface NormalizedSchema extends Schema { + js: boolean; + name: string; + fileName: string; + projectRoot: string; + routePath: string; + parsedTags: string[]; + appMain?: string; + appSourceRoot?: string; + unitTestRunner: 'vitest' | 'none'; +} diff --git a/packages/vue/src/generators/library/schema.json b/packages/vue/src/generators/library/schema.json new file mode 100644 index 00000000000000..e30d593201242e --- /dev/null +++ b/packages/vue/src/generators/library/schema.json @@ -0,0 +1,150 @@ +{ + "$schema": "http://json-schema.org/schema", + "cli": "nx", + "$id": "NxVueLibrary", + "title": "Create a Vue Library", + "description": "Create a Vue Library for an Nx workspace.", + "type": "object", + "examples": [ + { + "command": "nx g lib mylib --directory=myapp", + "description": "Generate `libs/myapp/mylib`" + }, + { + "command": "nx g lib mylib --appProject=myapp", + "description": "Generate a library with routes and add them to `myapp`" + } + ], + "properties": { + "name": { + "type": "string", + "description": "Library name", + "$default": { + "$source": "argv", + "index": 0 + }, + "x-prompt": "What name would you like to use for the library?", + "pattern": "(?:^@[a-zA-Z0-9-*~][a-zA-Z0-9-*._~]*\\/[a-zA-Z0-9-~][a-zA-Z0-9-._~]*|^[a-zA-Z][^:]*)$", + "x-priority": "important" + }, + "directory": { + "type": "string", + "description": "A directory where the lib is placed.", + "alias": "dir", + "x-priority": "important" + }, + "projectNameAndRootFormat": { + "description": "Whether to generate the project name and root directory as provided (`as-provided`) or generate them composing their values and taking the configured layout into account (`derived`).", + "type": "string", + "enum": ["as-provided", "derived"] + }, + "linter": { + "description": "The tool to use for running lint checks.", + "type": "string", + "enum": ["eslint", "none"], + "default": "eslint" + }, + "unitTestRunner": { + "type": "string", + "enum": ["vitest", "none"], + "description": "Test runner to use for unit tests.", + "x-prompt": "What unit test runner should be used?" + }, + "inSourceTests": { + "type": "boolean", + "default": false, + "description": "When using Vitest, separate spec files will not be generated and instead will be included within the source files." + }, + "tags": { + "type": "string", + "description": "Add tags to the library (used for linting).", + "alias": "t" + }, + "skipFormat": { + "description": "Skip formatting files.", + "type": "boolean", + "default": false, + "x-priority": "internal" + }, + "skipTsConfig": { + "type": "boolean", + "default": false, + "description": "Do not update `tsconfig.json` for development experience.", + "x-priority": "internal" + }, + "pascalCaseFiles": { + "type": "boolean", + "description": "Use pascal case component file name (e.g. `App.tsx`).", + "alias": "P", + "default": false + }, + "routing": { + "type": "boolean", + "description": "Generate library with routes." + }, + "appProject": { + "type": "string", + "description": "The application project to add the library route to.", + "alias": "a" + }, + "publishable": { + "type": "boolean", + "description": "Create a publishable library." + }, + "buildable": { + "type": "boolean", + "default": false, + "description": "Generate a buildable library that uses rollup to bundle.", + "x-deprecated": "Use the `bundler` option for greater control (none, vite, rollup)." + }, + "importPath": { + "type": "string", + "description": "The library name used to import it, like `@myorg/my-awesome-lib`." + }, + "component": { + "type": "boolean", + "description": "Generate a default component.", + "default": true + }, + "js": { + "type": "boolean", + "description": "Generate JavaScript files rather than TypeScript files.", + "default": false + }, + "strict": { + "type": "boolean", + "description": "Whether to enable tsconfig strict mode or not.", + "default": true + }, + "setParserOptionsProject": { + "type": "boolean", + "description": "Whether or not to configure the ESLint `parserOptions.project` option. We do not do this by default for lint performance reasons.", + "default": false + }, + "bundler": { + "type": "string", + "description": "The bundler to use. Choosing 'none' means this library is not buildable.", + "enum": ["none", "vite"], + "default": "none", + "x-prompt": "Which bundler would you like to use to build the library? Choose 'none' to skip build setup.", + "x-priority": "important" + }, + "skipPackageJson": { + "description": "Do not add dependencies to `package.json`.", + "type": "boolean", + "default": false, + "x-priority": "internal" + }, + "minimal": { + "description": "Create a Vue library with a minimal setup, no separate test files.", + "type": "boolean", + "default": false + }, + "simpleName": { + "description": "Don't include the directory in the name of the module of the library.", + "type": "boolean", + "default": false + } + }, + "required": ["name"] +} diff --git a/packages/vue/src/migrations/.gitkeep b/packages/vue/src/migrations/.gitkeep new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/packages/vue/src/utils/.gitkeep b/packages/vue/src/utils/.gitkeep new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/packages/vue/src/utils/create-ts-config.ts b/packages/vue/src/utils/create-ts-config.ts new file mode 100644 index 00000000000000..63102cab34f51b --- /dev/null +++ b/packages/vue/src/utils/create-ts-config.ts @@ -0,0 +1,76 @@ +import { Tree } from 'nx/src/generators/tree'; +import * as shared from '@nx/js/src/utils/typescript/create-ts-config'; +import { updateJson, writeJson } from 'nx/src/generators/utils/json'; + +export function createTsConfig( + host: Tree, + projectRoot: string, + type: 'app' | 'lib', + options: { + strict?: boolean; + style?: string; + bundler?: string; + rootProject?: boolean; + unitTestRunner?: string; + }, + relativePathToRootTsConfig: string +) { + const json = { + compilerOptions: {}, + files: [], + include: [], + references: [ + { + path: type === 'app' ? './tsconfig.app.json' : './tsconfig.lib.json', + }, + { + path: './tsconfig.node.json', + }, + { + path: './tsconfig.vitest.json', + }, + ], + } as any; + + // inline tsconfig.base.json into the project + if (options.rootProject) { + json.compileOnSave = false; + json.compilerOptions = { + ...shared.tsConfigBaseOptions, + ...json.compilerOptions, + }; + json.exclude = ['node_modules', 'tmp']; + } else { + json.extends = relativePathToRootTsConfig; + } + + writeJson(host, `${projectRoot}/tsconfig.json`, json); + + const tsconfigProjectPath = `${projectRoot}/tsconfig.${type}.json`; + if (options.bundler === 'vite' && host.exists(tsconfigProjectPath)) { + updateJson(host, tsconfigProjectPath, (json) => { + json.compilerOptions ??= {}; + + const types = new Set(json.compilerOptions.types ?? []); + types.add('node'); + types.add('vite/client'); + + json.compilerOptions.types = Array.from(types); + + return json; + }); + } else { + } +} + +export function extractTsConfigBase(host: Tree) { + shared.extractTsConfigBase(host); + + if (host.exists('vite.config.ts')) { + const vite = host.read('vite.config.ts').toString(); + host.write( + 'vite.config.ts', + vite.replace(`projects: []`, `projects: ['tsconfig.base.json']`) + ); + } +} diff --git a/packages/vue/src/utils/lint.ts b/packages/vue/src/utils/lint.ts new file mode 100644 index 00000000000000..1eb234b76f6435 --- /dev/null +++ b/packages/vue/src/utils/lint.ts @@ -0,0 +1,17 @@ +import { Linter } from 'eslint'; +import { + eslintPluginVueVersion, + eslintVersion, + vueEslintConfigPrettierVersion, + vueEslintConfigTypescriptVersion, +} from './versions'; + +export const extraEslintDependencies = { + dependencies: {}, + devDependencies: { + '@vue/eslint-config-prettier': vueEslintConfigPrettierVersion, + '@vue/eslint-config-typescript': vueEslintConfigTypescriptVersion, + eslint: eslintVersion, + 'eslint-plugin-vue': eslintPluginVueVersion, + }, +}; diff --git a/packages/vue/src/utils/versions.ts b/packages/vue/src/utils/versions.ts new file mode 100644 index 00000000000000..f1f7f469092e0a --- /dev/null +++ b/packages/vue/src/utils/versions.ts @@ -0,0 +1,7 @@ +export const nxVersion = require('../../package.json').version; +export const vueVersion = '^3.3.4'; + +export const vueEslintConfigPrettierVersion = '^8.0.0'; +export const vueEslintConfigTypescriptVersion = '^11.0.3'; +export const eslintVersion = '^8.46.0'; +export const eslintPluginVueVersion = '^9.16.1';