UNPKG

@nx/vite

Version:

The Nx Plugin for building and testing applications using Vite

211 lines (210 loc) • 10 kB
"use strict"; function _export(target, all) { for(var name in all)Object.defineProperty(target, name, { enumerable: true, get: all[name] }); } _export(exports, { default: function() { return _default; }, getBuildExtraArgs: function() { return getBuildExtraArgs; }, viteBuildExecutor: function() { return viteBuildExecutor; } }); const _extends = require("@swc/helpers/_/_extends"); const _devkit = require("@nx/devkit"); const _optionsutils = require("../../utils/options-utils"); const _js = require("@nx/js"); const _fs = require("fs"); const _path = require("path"); const _asynciterable = require("@nx/devkit/src/utils/async-iterable"); const _executorutils = require("../../utils/executor-utils"); const _tssolutionsetup = require("@nx/js/src/utils/typescript/ts-solution-setup"); async function* viteBuildExecutor(options, context) { var _resolved_build; process.env.VITE_CJS_IGNORE_WARNING = 'true'; // Allows ESM to be required in CJS modules. Vite will be published as ESM in the future. const { mergeConfig, build, resolveConfig, createBuilder } = await (0, _executorutils.loadViteDynamicImport)(); const projectRoot = context.projectsConfigurations.projects[context.projectName].root; const tsConfigForBuild = (0, _executorutils.createBuildableTsConfig)(projectRoot, options, context); const viteConfigPath = (0, _optionsutils.normalizeViteConfigFilePath)(context.root, projectRoot, options.configFile); const root = projectRoot === '.' || projectRoot === '' ? process.cwd() : (0, _path.relative)(context.cwd, (0, _devkit.joinPathFragments)(context.root, projectRoot)); const { buildOptions, otherOptions } = await getBuildExtraArgs(options); var _otherOptions_mode; const defaultMode = (_otherOptions_mode = otherOptions == null ? void 0 : otherOptions.mode) != null ? _otherOptions_mode : 'production'; var _process_env_NODE_ENV; const resolved = await resolveConfig({ configFile: viteConfigPath, mode: defaultMode }, 'build', defaultMode, (_process_env_NODE_ENV = process.env.NODE_ENV) != null ? _process_env_NODE_ENV : defaultMode); var _joinPathFragments; const outDir = (_joinPathFragments = (0, _devkit.joinPathFragments)((0, _devkit.offsetFromRoot)(projectRoot), options.outputPath)) != null ? _joinPathFragments : resolved == null ? void 0 : (_resolved_build = resolved.build) == null ? void 0 : _resolved_build.outDir; var _resolved_root; const buildConfig = mergeConfig({ // This should not be needed as it's going to be set in vite.config.ts // but leaving it here in case someone did not migrate correctly root: (_resolved_root = resolved.root) != null ? _resolved_root : root, configFile: viteConfigPath }, _extends._({ build: _extends._({ outDir }, buildOptions) }, otherOptions)); // New TS Solution already has a typecheck target if (!options.skipTypeCheck && !(0, _tssolutionsetup.isUsingTsSolutionSetup)()) { var _resolved_plugins; await (0, _executorutils.validateTypes)({ workspaceRoot: context.root, tsconfig: tsConfigForBuild, isVueProject: Boolean((_resolved_plugins = resolved.plugins) == null ? void 0 : _resolved_plugins.find((plugin)=>typeof plugin === 'object' && (plugin == null ? void 0 : plugin.name) === 'vite:vue')) }); } const builder = createBuilder !== undefined && options.useEnvironmentsApi ? await createBuilder(buildConfig) : { build: (inlineConfig)=>build(inlineConfig), environments: { build: buildConfig } }; let iterables = []; for (const env of Object.values(builder.environments)){ var _env_config; // This is needed to overwrite the resolve build config with executor options in Vite 6 if ((_env_config = env.config) == null ? void 0 : _env_config.build) { env.config.build = _extends._({}, env.config.build, buildConfig.build); } const watcherOrOutput = await builder.build(env); const libraryPackageJson = (0, _path.resolve)(projectRoot, 'package.json'); const rootPackageJson = (0, _path.resolve)(context.root, 'package.json'); // Here, we want the outdir relative to the workspace root. // So, we calculate the relative path from the workspace root to the outdir. const outDirRelativeToWorkspaceRoot = outDir.replaceAll('../', ''); const distPackageJson = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, 'package.json'); // Generate a package.json if option has been set. if (options.generatePackageJson) { var _builtPackageJson; if (context.projectGraph.nodes[context.projectName].type !== 'app') { _devkit.logger.warn((0, _devkit.stripIndents)`The project ${context.projectName} is using the 'generatePackageJson' option which is deprecated for library projects. It should only be used for applications. For libraries, configure the project to use the '@nx/dependency-checks' ESLint rule instead (https://nx.dev/nx-api/eslint-plugin/documents/dependency-checks).`); } const builtPackageJson = (0, _js.createPackageJson)(context.projectName, context.projectGraph, { target: context.targetName, root: context.root, isProduction: !options.includeDevDependenciesInPackageJson, skipOverrides: options.skipOverrides, skipPackageManager: options.skipPackageManager }); var _type; (_type = (_builtPackageJson = builtPackageJson).type) != null ? _type : _builtPackageJson.type = 'module'; (0, _devkit.writeJsonFile)(`${outDirRelativeToWorkspaceRoot}/package.json`, builtPackageJson); const packageManager = (0, _devkit.detectPackageManager)(context.root); const lockFile = (0, _js.createLockFile)(builtPackageJson, context.projectGraph, packageManager); (0, _fs.writeFileSync)(`${outDirRelativeToWorkspaceRoot}/${(0, _js.getLockFileName)(packageManager)}`, lockFile, { encoding: 'utf-8' }); } else if (options.generatePackageJson !== false && !(0, _fs.existsSync)(distPackageJson) && (0, _fs.existsSync)(libraryPackageJson) && rootPackageJson !== libraryPackageJson) { await (0, _js.copyAssets)({ outputPath: outDirRelativeToWorkspaceRoot, assets: [ { input: projectRoot, output: '.', glob: 'package.json' } ] }, context); } const iterable = (0, _asynciterable.createAsyncIterable)(({ next, done })=>{ if ('on' in watcherOrOutput) { let success = true; watcherOrOutput.on('event', (event)=>{ if (event.code === 'START') { success = true; } else if (event.code === 'ERROR') { success = false; } else if (event.code === 'END') { next({ success }); } // result must be closed when present. // see https://rollupjs.org/guide/en/#rollupwatch if ('result' in event && event.result) { event.result.close(); } }); } else { var _watcherOrOutput_, _output_; const output = (watcherOrOutput == null ? void 0 : watcherOrOutput['output']) || (watcherOrOutput == null ? void 0 : (_watcherOrOutput_ = watcherOrOutput[0]) == null ? void 0 : _watcherOrOutput_.output); const fileName = (output == null ? void 0 : (_output_ = output[0]) == null ? void 0 : _output_.fileName) || 'main.cjs'; const outfile = (0, _path.resolve)(outDirRelativeToWorkspaceRoot, fileName); next({ success: true, outfile }); done(); } }); iterables.push(iterable); } return yield* (0, _asynciterable.combineAsyncIterables)(iterables.shift(), ...iterables != null ? iterables : []); } async function getBuildExtraArgs(options) { // support passing extra args to vite cli const schema = await Promise.resolve().then(()=>require("./schema.json")); const extraArgs = {}; for (const key of Object.keys(options)){ if (!schema.properties[key]) { extraArgs[key] = options[key]; } } const buildOptions = {}; const buildSchemaKeys = [ 'target', 'polyfillModulePreload', 'modulePreload', 'outDir', 'assetsDir', 'assetsInlineLimit', 'cssCodeSplit', 'cssTarget', 'cssMinify', 'sourcemap', 'minify', 'terserOptions', 'rollupOptions', 'commonjsOptions', 'dynamicImportVarsOptions', 'write', 'emptyOutDir', 'copyPublicDir', 'manifest', 'lib', 'ssr', 'ssrManifest', 'ssrEmitAssets', 'reportCompressedSize', 'chunkSizeWarningLimit', 'watch' ]; const otherOptions = {}; for (const key of Object.keys(extraArgs)){ if (buildSchemaKeys.includes(key)) { buildOptions[key] = extraArgs[key]; } else { otherOptions[key] = extraArgs[key]; } } var _options_watch; buildOptions['watch'] = (_options_watch = options.watch) != null ? _options_watch : undefined; return { buildOptions, otherOptions }; } const _default = viteBuildExecutor; //# sourceMappingURL=build.impl.js.map