@nx/vite
Version:
174 lines (173 loc) • 9.32 kB
JavaScript
Object.defineProperty(exports, "nxViteTsPaths", {
enumerable: true,
get: function() {
return nxViteTsPaths;
}
});
const _devkit = require("@nx/devkit");
const _nodefs = require("node:fs");
const _nodepath = require("node:path");
const _tsconfigpaths = require("tsconfig-paths");
const _buildablelibsutils = require("@nx/js/src/utils/buildable-libs-utils");
const _nxvitebuildcoordinationplugin = require("./nx-vite-build-coordination.plugin");
const _nxtsconfigpathsfindfile = require("../src/utils/nx-tsconfig-paths-find-file");
const _tssolutionsetup = require("@nx/js/src/utils/typescript/ts-solution-setup");
function nxViteTsPaths(options = {}) {
var _options, _options1, _options2;
let foundTsConfigPath;
let matchTsPathEsm;
let matchTsPathFallback;
let tsConfigPathsEsm;
let tsConfigPathsFallback;
var _extensions;
(_extensions = (_options = options).extensions) != null ? _extensions : _options.extensions = [
'.ts',
'.tsx',
'.js',
'.jsx',
'.json',
'.mts',
'.mjs',
'.cts',
'.cjs',
'.css',
'.scss',
'.less'
];
var _mainFields;
(_mainFields = (_options1 = options).mainFields) != null ? _mainFields : _options1.mainFields = [
[
'exports',
'.',
'import'
],
'module',
'main'
];
var _buildLibsFromSource;
(_buildLibsFromSource = (_options2 = options).buildLibsFromSource) != null ? _buildLibsFromSource : _options2.buildLibsFromSource = true;
let projectRoot = '';
return {
name: 'nx-vite-ts-paths',
// Ensure the resolveId aspect of the plugin is called before vite's internal resolver
// Otherwise, issues can arise with Yarn Workspaces and Pnpm Workspaces
enforce: 'pre',
async configResolved (config) {
projectRoot = config.root;
const projectRootFromWorkspaceRoot = (0, _nodepath.relative)(_devkit.workspaceRoot, projectRoot);
var _process_env_NX_TASK_TARGET_TARGET, _process_env_NX_TSCONFIG_PATH;
foundTsConfigPath = getTsConfig((_process_env_NX_TSCONFIG_PATH = process.env.NX_TSCONFIG_PATH) != null ? _process_env_NX_TSCONFIG_PATH : (0, _nodepath.join)(_devkit.workspaceRoot, 'tmp', projectRootFromWorkspaceRoot, (_process_env_NX_TASK_TARGET_TARGET = process.env.NX_TASK_TARGET_TARGET) != null ? _process_env_NX_TASK_TARGET_TARGET : 'build', 'tsconfig.generated.json'));
if (!foundTsConfigPath) return;
if (!options.buildLibsFromSource && !global.NX_GRAPH_CREATION && config.mode !== 'test') {
const projectGraph = await (0, _devkit.createProjectGraphAsync)({
exitOnError: false,
resetDaemonClient: true
});
const { dependencies } = (0, _buildablelibsutils.calculateProjectBuildableDependencies)(undefined, projectGraph, _devkit.workspaceRoot, process.env.NX_TASK_TARGET_PROJECT, // When using incremental building and the serve target is called
// we need to get the deps for the 'build' target instead.
process.env.NX_TASK_TARGET_TARGET === 'serve' ? 'build' : process.env.NX_TASK_TARGET_TARGET, process.env.NX_TASK_TARGET_CONFIGURATION);
// This tsconfig is used via the Vite ts paths plugin.
// It can be also used by other user-defined Vite plugins (e.g. for creating type declaration files).
foundTsConfigPath = (0, _buildablelibsutils.createTmpTsConfig)(foundTsConfigPath, _devkit.workspaceRoot, (0, _nodepath.relative)(_devkit.workspaceRoot, projectRoot), dependencies, true);
if (config.command === 'serve') {
const buildableLibraryDependencies = dependencies.filter((dep)=>dep.node.type === 'lib').map((dep)=>dep.node.name).join(',');
const buildCommand = `npx nx run-many --target=${process.env.NX_TASK_TARGET_TARGET} --projects=${buildableLibraryDependencies}`;
config.plugins.push((0, _nxvitebuildcoordinationplugin.nxViteBuildCoordinationPlugin)({
buildCommand
}));
}
}
const parsed = (0, _tsconfigpaths.loadConfig)(foundTsConfigPath);
logIt('first parsed tsconfig: ', parsed);
if (parsed.resultType === 'failed') {
throw new Error(`Failed loading tsconfig at ${foundTsConfigPath}`);
}
tsConfigPathsEsm = parsed;
matchTsPathEsm = (0, _tsconfigpaths.createMatchPath)(parsed.absoluteBaseUrl, parsed.paths, options.mainFields);
const rootLevelTsConfig = getTsConfig((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.base.json'));
const rootLevelParsed = (0, _tsconfigpaths.loadConfig)(rootLevelTsConfig);
logIt('fallback parsed tsconfig: ', rootLevelParsed);
if (rootLevelParsed.resultType === 'success') {
tsConfigPathsFallback = rootLevelParsed;
matchTsPathFallback = (0, _tsconfigpaths.createMatchPath)(rootLevelParsed.absoluteBaseUrl, rootLevelParsed.paths, [
'main',
'module'
]);
}
},
resolveId (importPath) {
// Let other resolvers handle this path.
if (!foundTsConfigPath) return null;
let resolvedFile;
try {
resolvedFile = matchTsPathEsm(importPath);
} catch (e) {
logIt('Using fallback path matching.');
resolvedFile = matchTsPathFallback == null ? void 0 : matchTsPathFallback(importPath);
}
if (!resolvedFile || !(0, _nodefs.existsSync)(resolvedFile)) {
if (tsConfigPathsEsm || tsConfigPathsFallback) {
logIt(`Unable to resolve ${importPath} with tsconfig paths. Using fallback file matching.`);
resolvedFile = loadFileFromPaths(tsConfigPathsEsm, importPath) || loadFileFromPaths(tsConfigPathsFallback, importPath);
} else {
logIt(`Unable to resolve ${importPath} with tsconfig paths`);
}
}
logIt(`Resolved ${importPath} to ${resolvedFile}`);
// Returning null defers to other resolveId functions and eventually the default resolution behavior
// https://rollupjs.org/plugin-development/#resolveid
return resolvedFile || null;
},
async writeBundle (options) {
if ((0, _tssolutionsetup.isUsingTsSolutionSetup)()) return;
const outDir = options.dir || 'dist';
const src = (0, _nodepath.resolve)(projectRoot, 'package.json');
if ((0, _nodefs.existsSync)(src)) {
const dest = (0, _nodepath.join)(outDir, 'package.json');
try {
(0, _nodefs.copyFileSync)(src, dest);
} catch (err) {
console.error('Error copying package.json:', err);
}
}
}
};
function getTsConfig(preferredTsConfigPath) {
return [
(0, _nodepath.resolve)(preferredTsConfigPath),
(0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.base.json')),
(0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'tsconfig.json')),
(0, _nodepath.resolve)((0, _nodepath.join)(_devkit.workspaceRoot, 'jsconfig.json'))
].find((tsPath)=>{
if ((0, _nodefs.existsSync)(tsPath)) {
logIt('Found tsconfig at', tsPath);
return tsPath;
}
});
}
function logIt(...msg) {
if (process.env.NX_VERBOSE_LOGGING === 'true' && (options == null ? void 0 : options.debug) !== false) {
console.debug('\n[Nx Vite TsPaths]', ...msg);
}
}
function loadFileFromPaths(tsconfig, importPath) {
logIt(`Trying to resolve file from config in ${tsconfig.configFileAbsolutePath}`);
let resolvedFile;
for(const alias in tsconfig.paths){
const paths = tsconfig.paths[alias];
const normalizedImport = alias.replace(/\/\*$/, '');
if (importPath === normalizedImport || importPath.startsWith(normalizedImport + '/')) {
const joinedPath = (0, _devkit.joinPathFragments)(tsconfig.absoluteBaseUrl, paths[0].replace(/\/\*$/, ''));
resolvedFile = (0, _nxtsconfigpathsfindfile.findFile)(importPath.replace(normalizedImport, joinedPath), options.extensions);
if (resolvedFile === undefined && options.extensions.some((ext)=>importPath.endsWith(ext))) {
const foundExtension = options.extensions.find((ext)=>importPath.endsWith(ext));
const pathWithoutExtension = importPath.replace(normalizedImport, joinedPath).slice(0, -foundExtension.length);
resolvedFile = (0, _nxtsconfigpathsfindfile.findFile)(pathWithoutExtension, options.extensions);
}
}
}
return resolvedFile;
}
}
//# sourceMappingURL=nx-tsconfig-paths.plugin.js.map
;