Skip to content

Commit

Permalink
fixed generated output for complex dir structure
Browse files Browse the repository at this point in the history
  • Loading branch information
victorgarciaesgi committed Oct 7, 2021
1 parent bb2d519 commit 7f30258
Show file tree
Hide file tree
Showing 36 changed files with 9,957 additions and 676 deletions.
19 changes: 19 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { compilerOptions } = require('./tsconfig');

module.exports = {
preset: '@nuxt/test-utils',
moduleFileExtensions: ['js', 'ts', 'json'],
testRegex: '(/__tests__/.+|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testURL: 'http://localhost/',
collectCoverage: false,
transformIgnorePatterns: ['/node_modules/(?!lodash-es|log-symbols)/'],
globals: {
'ts-jest': {
tsconfig: './tsconfig.json',
},
},
testEnvironment: 'jsdom',
};
16 changes: 14 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nuxt-typed-router",
"version": "0.2.22",
"version": "0.2.24",
"description": "Provide autocompletion for pages route names generated by Nuxt router",
"main": "lib/module.js",
"keywords": [
Expand All @@ -15,7 +15,9 @@
"dev": "tsc -p ./tsconfig.json --pretty --watch",
"build": "rimraf lib && rimraf types && tsc -p ./tsconfig.json --pretty",
"copy-files": "copyfiles -u 1 ./src/**/*.js ./lib",
"prepublish": "yarn build"
"prepublish": "yarn build",
"test": "jest",
"test:reset": "yarn test --updateSnapshot"
},
"publishConfig": {
"access": "public"
Expand All @@ -41,17 +43,27 @@
"typings": "types/index.d.ts",
"dependencies": {
"chalk": "^4.1.2",
"jest": "^27.2.4",
"lodash": "^4.17.21",
"log-symbols": "^5.0.0",
"prettier": "^2.4.1"
},
"devDependencies": {
"@babel/plugin-transform-runtime": "^7.15.8",
"@babel/preset-env": "^7.15.8",
"@nuxt/test-utils": "^0.2.2",
"@nuxt/types": "^2.15.8",
"@types/jest": "^27.0.2",
"@types/lodash": "^4.14.173",
"@types/node": "^15.12.4",
"@types/prettier": "^2.3.2",
"babel-jest": "^27.2.4",
"copyfiles": "^2.4.0",
"core-js": "^3.18.2",
"nuxt": "^2.15.8",
"playwright": "^1.15.2",
"rimraf": "^3.0.2",
"ts-jest": "^27.0.5",
"typescript": "^4.4.3",
"vue-router": "^3.5.2"
}
Expand Down
156 changes: 86 additions & 70 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,88 +11,104 @@ import {
extractUnMatchingSiblings,
transformRouteNames,
} from './utils';
import { ModuleThis } from '@nuxt/types/config/module';

const typedRouterModule: Module<NuxtTypedRouterOptions> = function (moduleOptions) {
const {
filePath = `${this.options.srcDir}/__routes.js`,
routesObjectName = 'routerPagesNames',
stripAtFromName = false,
}: NuxtTypedRouterOptions = { ...this.options.typedRouter, ...moduleOptions };

this.nuxt.hook('build:extendRoutes', async (existingRoutes: NuxtRouteConfig[]) => {
try {
// Redirect with @

this.extendRoutes(async (routes: NuxtRouteConfig[]) => {
transformRouteNames(routes, stripAtFromName);
function routeHook(
this: ModuleThis,
filePath: string,
routesObjectName: string,
stripAtFromName: boolean
) {
try {
// Redirect with @

let routesObjectString = '{';
let routeObjectJs: Record<string, any> = {};
this.extendRoutes(async (routes: NuxtRouteConfig[]) => {
transformRouteNames(routes, stripAtFromName);

const recursiveTypedRoutes = (
route: NuxtRouteConfig,
level: number,
routeObject: Record<string, any>,
siblings?: NuxtRouteConfig[],
parentName?: string,
hadMatching?: boolean
) => {
const routeName = route.name;
const matchingSiblings = extractMatchingSiblings(route, siblings);
const haveMatchingSiblings = !!matchingSiblings?.length;
let routesObjectString = '{';
let routeObjectJs: Record<string, any> = {};

if (
(route.children && !haveMatchingSiblings) ||
(!route.children && haveMatchingSiblings)
) {
let childrenChunks = haveMatchingSiblings ? matchingSiblings : route.children;
const splittedPaths = route.path.split('/');
const parentPath = splittedPaths[splittedPaths.length - 1];
const nameKey = camelCase(parentPath || 'index');
routesObjectString += `${nameKey}:{`;
routeObject[nameKey] = {};
childrenChunks?.map((r) =>
recursiveTypedRoutes(
r,
level + 1,
routeObject[nameKey],
extractUnMatchingSiblings(route, siblings),
nameKey,
haveMatchingSiblings
)
);
routesObjectString += '},';
} else if (routeName) {
let splitted = routeName.split('-');
const recursiveTypedRoutes = (
route: NuxtRouteConfig,
level: number,
routeObject: Record<string, any>,
siblings?: NuxtRouteConfig[],
parentName?: string,
hadMatching?: boolean
) => {
const matchingSiblings = extractMatchingSiblings(route, siblings);
const haveMatchingSiblings = !!matchingSiblings?.length && route.path !== '/';
const chunkArray = route.chunkName?.split('/') ?? [];
const isRootSibling = chunkArray[chunkArray?.length - 1] === 'index';
if (
(route.children && !haveMatchingSiblings) ||
(!route.children && haveMatchingSiblings && isRootSibling)
) {
let childrenChunks = haveMatchingSiblings ? matchingSiblings : route.children;
const splittedPaths = route.path.split('/');
const parentPath = splittedPaths[splittedPaths.length - 1];
const nameKey = camelCase(parentPath || 'index');
routesObjectString += `${nameKey}:{`;
routeObject[nameKey] = {};
childrenChunks?.map((r) =>
recursiveTypedRoutes(
r,
level + 1,
routeObject[nameKey],
extractUnMatchingSiblings(route, siblings),
nameKey,
haveMatchingSiblings
)
);
routesObjectString += '},';
} else {
let splitted: string[] = [];
if (route.name) {
splitted = route.name.split('-');
splitted = splitted.slice(level, splitted.length);
if (splitted[0] === parentName) {
splitted.splice(0, 1);
}
const keyName = route.path === '' ? 'index' : camelCase(splitted.join('-')) || 'index';
routesObjectString += `'${keyName}': '${routeName}',`;
routeObject[keyName] = routeName;
}
};
routes.map((r) =>
recursiveTypedRoutes(
r,
0,
routeObjectJs,
routes?.filter((f) => f.path !== r.path)
)
);
routesObjectString += '}';
const keyName = route.path === '' ? 'index' : camelCase(splitted.join('-')) || 'index';
routesObjectString += `'${keyName}': '${route.name}',`;
routeObject[keyName] = route.name;
}
};
routes.map((r) =>
recursiveTypedRoutes(
r,
0,
routeObjectJs,
routes?.filter((f) => f.path !== r.path)
)
);
routesObjectString += '}';

const templateRoutes = `export const ${routesObjectName} = ${routesObjectString};`;
const templateRoutes = `export const ${routesObjectName} = ${routesObjectString};`;

await saveRoutesFiles(filePath, templateRoutes);
});
await saveRoutesFiles(filePath, templateRoutes);
});

// Typed router
} catch (e) {
console.error(chalk.red('Error while generating routes definitions model'), '\n' + e);
}
}

const typedRouterModule: Module<NuxtTypedRouterOptions> = function (moduleOptions) {
const {
filePath = `${this.options.srcDir}/__routes.js`,
routesObjectName = 'routerPagesNames',
stripAtFromName = false,
}: NuxtTypedRouterOptions = { ...this.options.typedRouter, ...moduleOptions };

// Typed router
} catch (e) {
console.error(chalk.red('Error while generating routes definitions model'), '\n' + e);
}
});
this.nuxt.hook('build:before', () =>
routeHook.call(this, filePath, routesObjectName, stripAtFromName)
);
this.nuxt.hook('build:extendRoutes', () =>
routeHook.call(this, filePath, routesObjectName, stripAtFromName)
);
};

module.exports = typedRouterModule;
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function extractMatchingSiblings(
) {
return siblingRoutes?.filter((s) => {
const chunkName = extractChunkMain(mainRoute.chunkName);
if (chunkName) {
if (chunkName && s.name) {
const siblingChunkName = extractChunkMain(s.chunkName);
if (!siblingChunkName) return false;
return chunkName === siblingChunkName;
Expand Down
Binary file added test/.DS_Store
Binary file not shown.
15 changes: 0 additions & 15 deletions test/__routes.js

This file was deleted.

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
16 changes: 16 additions & 0 deletions test/fixtures/basic/__routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const routerPagesNames = {
activate: 'activate',
rootPage: 'rootPage',
childOne: {
index: 'parent-child-one',
childOneChildOneSubOne: 'parent-child-one-child-one-sub-one',
childOneChildOneSubTwo: 'parent-child-one-child-one-sub-two',
user: { index: 'parent-child-one-child-one-sub-one-user' },
},
childTwo: {
index: 'parent-child-two',
childTwoChildOneSubOne: 'parent-child-two-child-one-sub-one',
},
index: 'index',
all: 'all',
};
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion test/nuxt.config.js → test/fixtures/basic/nuxt.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import moduleRouter from '../lib/module';
import moduleRouter from '../../../lib/module';

export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions test/pages/index.vue → test/fixtures/basic/pages/index.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<template>
<Tutorial/>
<div></div>
</template>

<script>
export default {}
export default {};
</script>
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Empty file.
Empty file.
File renamed without changes.
File renamed without changes.
File renamed without changes.
21 changes: 21 additions & 0 deletions test/unit/__snapshots__/root.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Init route file should generate to correct tree for the pages folder 1`] = `
"export const routerPagesNames = {
activate: 'activate',
rootPage: 'rootPage',
childOne: {
index: 'parent-child-one',
childOneChildOneSubOne: 'parent-child-one-child-one-sub-one',
childOneChildOneSubTwo: 'parent-child-one-child-one-sub-two',
user: { index: 'parent-child-one-child-one-sub-one-user' },
},
childTwo: {
index: 'parent-child-two',
childTwoChildOneSubOne: 'parent-child-two-child-one-sub-one',
},
index: 'index',
all: 'all',
};
"
`;
21 changes: 21 additions & 0 deletions test/unit/root.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { createPage, setupTest } from '@nuxt/test-utils';
import 'core-js';
import { readFile } from 'fs/promises';

describe('Init route file', () => {
setupTest({
browser: true,
build: true,
setupTimeout: 100000,
rootDir: 'test/fixtures/basic',
config: {
server: {
port: 2310,
},
},
});
it('should generate to correct tree for the pages folder', async () => {
const routeFile = await readFile('test/fixtures/basic/__routes.js', 'utf-8');
expect(routeFile).toMatchSnapshot();
});
});
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"es2017.object",
"es7"
],
"types": ["node"]
"types": ["node", "jest"]
},
"include": ["./src/**/*.ts"]
}

0 comments on commit 7f30258

Please sign in to comment.