UNPKG

@nx/react

Version:

The React plugin for Nx contains executors and generators for managing React applications and libraries within an Nx workspace. It provides: - Integration with libraries such as Jest, Vitest, Playwright, Cypress, and Storybook. - Generators for applica

62 lines (61 loc) 2.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.updateAppRoutes = updateAppRoutes; const devkit_1 = require("@nx/devkit"); const ast_utils_1 = require("../../../utils/ast-utils"); const ast_utils_2 = require("../../../utils/ast-utils"); const maybe_js_1 = require("../../../utils/maybe-js"); const versions_1 = require("../../../utils/versions"); const ensure_typescript_1 = require("@nx/js/src/utils/typescript/ensure-typescript"); let tsModule; function updateAppRoutes(host, options) { if (!options.appMain || !options.appSourceRoot) { return () => { }; } const { content, source } = readComponent(host, options.appMain); const componentImportPath = (0, ast_utils_1.findComponentImportPath)('App', source); if (!componentImportPath) { throw new Error(`Could not find App component in ${options.appMain} (Hint: you can omit --appProject, or make sure App exists)`); } const appComponentPath = (0, devkit_1.joinPathFragments)(options.appSourceRoot, (0, maybe_js_1.maybeJs)(options, `${componentImportPath}.tsx`)); const routerTask = (0, devkit_1.addDependenciesToPackageJson)(host, { 'react-router-dom': versions_1.reactRouterDomVersion, }, {}); // addBrowserRouterToMain const isRouterPresent = content.match(/react-router-dom/); if (!isRouterPresent) { const changes = (0, devkit_1.applyChangesToString)(content, (0, ast_utils_1.addBrowserRouter)(options.appMain, source)); host.write(options.appMain, changes); } // addInitialAppRoutes { const { content: componentContent, source: componentSource } = readComponent(host, appComponentPath); const isComponentRouterPresent = componentContent.match(/react-router-dom/); if (!isComponentRouterPresent) { const changes = (0, devkit_1.applyChangesToString)(componentContent, (0, ast_utils_2.addInitialRoutes)(appComponentPath, componentSource)); host.write(appComponentPath, changes); } } // addNewAppRoute { const { content: componentContent, source: componentSource } = readComponent(host, appComponentPath); const changes = (0, devkit_1.applyChangesToString)(componentContent, (0, ast_utils_1.addRoute)(appComponentPath, componentSource, { routePath: options.routePath, componentName: (0, devkit_1.names)(options.name).className, moduleName: options.importPath, })); host.write(appComponentPath, changes); } return routerTask; } function readComponent(host, path) { if (!host.exists(path)) { throw new Error(`Cannot find ${path}`); } if (!tsModule) { tsModule = (0, ensure_typescript_1.ensureTypescript)(); } const content = host.read(path, 'utf-8'); const source = tsModule.createSourceFile(path, content, tsModule.ScriptTarget.Latest, true); return { content, source }; }