Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nuxt): correct outputs for nuxt and vite #20627

Merged
merged 3 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@
"@nx/eslint": "file:../eslint",
"@nx/vue": "file:../vue"
},
"peerDependencies": {
"vite": "^5.0.0"
},
"publishConfig": {
"access": "public"
},
"peerDependencies": {}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ export default defineConfig({
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],

reporters: ['default'],
coverage: {
reportsDirectory: '../coverage/my-app',
provider: 'v8',
Expand Down
14 changes: 6 additions & 8 deletions packages/nuxt/src/plugins/__snapshots__/plugin.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ exports[`@nx/nuxt/plugin not root project should create nodes 1`] = `
"^build-something",
],
"inputs": [
"default",
"production",
"^production",
{
"externalDependencies": [
Expand All @@ -25,7 +25,7 @@ exports[`@nx/nuxt/plugin not root project should create nodes 1`] = `
"cwd": "my-app",
},
"outputs": [
"{options.outputPath}",
"{workspaceRoot}/dist/my-app/",
],
},
"my-serve": {
Expand All @@ -50,8 +50,7 @@ exports[`@nx/nuxt/plugin not root project should create nodes 1`] = `
"cwd": "my-app",
},
"outputs": [
"{options.reportsDirectory}",
"{workspaceRoot}/coverage/my-app",
"{workspaceRoot}/coverage/{projectRoot}",
],
},
},
Expand All @@ -73,7 +72,7 @@ exports[`@nx/nuxt/plugin root project should create nodes 1`] = `
"^build",
],
"inputs": [
"default",
"production",
"^production",
{
"externalDependencies": [
Expand All @@ -85,7 +84,7 @@ exports[`@nx/nuxt/plugin root project should create nodes 1`] = `
"cwd": ".",
},
"outputs": [
"{options.outputPath}",
"dist/my-app/",
],
},
"serve": {
Expand All @@ -110,8 +109,7 @@ exports[`@nx/nuxt/plugin root project should create nodes 1`] = `
"cwd": ".",
},
"outputs": [
"{options.reportsDirectory}",
"{projectRoot}/coverage",
"{workspaceRoot}/coverage/{projectRoot}",
],
},
},
Expand Down
20 changes: 13 additions & 7 deletions packages/nuxt/src/plugins/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,35 @@ import { CreateNodesContext } from '@nx/devkit';
import { createNodes } from './plugin';
import { TempFs } from 'nx/src/internal-testing-utils/temp-fs';

jest.mock('@nuxt/kit', () => ({
loadNuxtConfig: jest.fn().mockImplementation(() => {
jest.mock('vite', () => ({
loadConfigFromFile: jest.fn().mockImplementation(() => {
return Promise.resolve({
path: 'nuxt.config.ts',
path: 'vite.config.ts',
config: {},
dependencies: [],
});
}),
}));

jest.mock('@nuxt/kit', () => ({
loadNuxtConfig: jest.fn().mockImplementation(() => {
return Promise.resolve({
buildDir: '../dist/my-app/.nuxt',
});
}),
}));

jest.mock('../utils/executor-utils', () => ({
loadNuxtKitDynamicImport: jest.fn().mockResolvedValue({
loadNuxtConfig: jest.fn().mockResolvedValue({
path: 'nuxt.config.ts',
config: {},
dependencies: [],
buildDir: '../dist/my-app/.nuxt',
}),
}),
}));

describe('@nx/nuxt/plugin', () => {
let createNodesFunction = createNodes[1];
let context: CreateNodesContext;

describe('root project', () => {
beforeEach(async () => {
context = {
Expand Down
103 changes: 67 additions & 36 deletions packages/nuxt/src/plugins/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,19 @@ import {
CreateNodesContext,
detectPackageManager,
joinPathFragments,
offsetFromRoot,
readJsonFile,
TargetConfiguration,
workspaceRoot,
writeJsonFile,
} from '@nx/devkit';
import { basename, dirname, join } from 'path';
import { basename, dirname, isAbsolute, join, relative } from 'path';
import { projectGraphCacheDirectory } from 'nx/src/utils/cache-directory';
import { getNamedInputs } from '@nx/devkit/src/utils/get-named-inputs';
import { existsSync, readdirSync } from 'fs';
import { loadNuxtKitDynamicImport } from '../utils/executor-utils';
import { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';
import { getLockFileName } from '@nx/js';
import { loadConfigFromFile, UserConfig } from 'vite';

const cachePath = join(projectGraphCacheDirectory, 'nuxt.hash');
const targetsCache = existsSync(cachePath) ? readTargetsCache() : {};
Expand Down Expand Up @@ -90,11 +91,36 @@ async function buildNuxtTargets(
options: NuxtPluginOptions,
context: CreateNodesContext
) {
let viteConfig:
| {
path: string;
config: UserConfig;
dependencies: string[];
}
| undefined;
if (
existsSync(
joinPathFragments(context.workspaceRoot, projectRoot, 'vitest.config.ts')
)
) {
viteConfig = await loadConfigFromFile(
{
command: 'build',
mode: 'production',
},
joinPathFragments(context.workspaceRoot, projectRoot, 'vitest.config.ts')
);
}

const nuxtConfig: {
buildDir: string;
} = await getInfoFromNuxtConfig(configFilePath, context, projectRoot);

const { buildOutputs, testOutputs } = getOutputs(projectRoot, nuxtConfig);
const { buildOutputs, testOutputs } = getOutputs(
nuxtConfig,
viteConfig?.config,
projectRoot
);

const namedInputs = getNamedInputs(projectRoot, context);

Expand Down Expand Up @@ -133,7 +159,7 @@ function buildTarget(
dependsOn: [`^${buildTargetName}`],
inputs: [
...('production' in namedInputs
? ['default', '^production']
? ['production', '^production']
: ['default', '^default']),

{
Expand Down Expand Up @@ -187,59 +213,64 @@ async function getInfoFromNuxtConfig(
buildDir: string;
}> {
const { loadNuxtConfig } = await loadNuxtKitDynamicImport();

const config = await loadNuxtConfig({
cwd: joinPathFragments(context.workspaceRoot, projectRoot),
configFile: basename(configFilePath),
});

return {
// to preserve only the relative path from the workspace root
// because nuxt automatically prepends the rootDir to buildDir
buildDir: config?.buildDir?.replace(config?.rootDir, ''),
buildDir: config?.buildDir,
};
}

function getOutputs(
projectRoot: string,
nuxtConfig: {
buildDir: string;
}
nuxtConfig: { buildDir: string },
viteConfig: UserConfig,
projectRoot: string
): {
buildOutputs: string[];
outputPath: string;
testOutputs: string[];
reportsDirectory: string;
} {
const buildOutputs = ['{options.outputPath}'];
const testOutputs = ['{options.reportsDirectory}'];
const reportsDirectory =
normalizeOutputPath(
viteConfig?.['test']?.coverage?.reportsDirectory,
projectRoot
) ?? '{workspaceRoot}/coverage/{projectRoot}';

function getOutput(path: string, projectRoot: string): string {
if (path.startsWith('..')) {
return join('{workspaceRoot}', join(projectRoot, path));
} else {
return join('{projectRoot}', path);
}
}

let distPath = undefined;
let nuxtBuildDir = nuxtConfig?.buildDir;
if (nuxtConfig?.buildDir && basename(nuxtConfig?.buildDir) === '.nuxt') {
// buildDir will most probably be `../dist/my-app/.nuxt`
// we want the "general" outputPath to be `../dist/my-app`
distPath = nuxtConfig.buildDir.replace(basename(nuxtConfig.buildDir), '');
buildOutputs.push(getOutput(distPath, projectRoot));
nuxtBuildDir = nuxtConfig.buildDir.replace(
basename(nuxtConfig.buildDir),
''
);
}
const buildOutputPath =
normalizeOutputPath(nuxtBuildDir, projectRoot) ??
'{workspaceRoot}/dist/{projectRoot}';

const outputPath = distPath ?? joinPathFragments('dist', projectRoot);

const reportsDirectory = joinPathFragments(
offsetFromRoot(projectRoot),
'coverage',
projectRoot
);

testOutputs.push(getOutput(reportsDirectory, projectRoot));
return {
buildOutputs: [buildOutputPath],
testOutputs: [reportsDirectory],
};
}

return { buildOutputs, outputPath, testOutputs, reportsDirectory };
function normalizeOutputPath(
outputPath: string | undefined,
projectRoot: string
): string | undefined {
if (!outputPath) return undefined;
if (isAbsolute(outputPath)) {
return `{workspaceRoot}/${relative(workspaceRoot, outputPath)}`;
} else {
if (outputPath.startsWith('..')) {
return join('{workspaceRoot}', join(projectRoot, outputPath));
} else {
return outputPath;
}
}
}

function normalizeOptions(options: NuxtPluginOptions): NuxtPluginOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export default defineConfig({
cache: { dir: '../node_modules/.vitest' },
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
reporters: ['default'],
coverage: { reportsDirectory: '../coverage/my-lib', provider: 'v8' },
},
});
Expand Down Expand Up @@ -58,6 +59,10 @@ export default defineConfig({
// See: https://vitejs.dev/guide/build.html#library-mode
build: {
outDir: '../dist/my-lib',
reportCompressedSize: true,
commonjsOptions: {
transformMixedEsModules: true,
},
lib: {
// Could also be a dictionary or array of multiple entry points.
entry: 'src/index.ts',
Expand All @@ -81,6 +86,7 @@ export default defineConfig({
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],

reporters: ['default'],
coverage: {
reportsDirectory: '../coverage/my-lib',
provider: 'v8',
Expand Down
Loading