File naming in Nest.js

Viewed 9957

This question is about code styling in Nestjs. This framework suggests file naming lowercase letters and across the dot.

Example:

file user.service.ts

export class UserService {
}

another file

import { UserService } from './user.service'

In most cases every file contains one class. I find it convenient to export this class as default and then import the file with the same name

file UserService.ts

export default class UserService {
}

another file

import UserService from './UserService'

Because it is faster and easier.

Could you argue to me why I should not do this? Also I don’t understand why the only entity in a file is not exported as default. Are you comfortable working with file names in Nest JS?

UPD. One more question: If I have a class name consisting of several words. For example "UserRoleService". What should I name this file?

userrole.service.ts

user-role.service.ts

user_role.service.ts

user.role.service.ts

It looks weird and not readable. I think CamelCase would be preferable but here we come back where we started

2 Answers

I came a cross this old question, and I think it worths providing this answer for next visitors.

Like @Jay McDoiel mentioned, this is a very opinionated choice. Either way is correct.

However, I found out that NestJS library used hyphen-separated user-role.service.ts file naming as its convention.

Check out my the attached photo below

enter image description here

This is a very opinionated question which deserves an opinionated answer.

File Names

The file names are separated as they are for several reasons.

1) it's how Angular does it and Nest is inspired by Angular

2) it means that OSs that treat uppercase and lowercase file names as the same do not get confused (like MacOS)

3) it gives the dev an easy separation point in the file name to look at

4) some tooling in file editors can show different icons depending on the file name. .ts might not mean anything other than a typescript file, but .service.ts means a Service file written in typescript. (Material Icon Theme with VSCode gives different icons)

Exports

The other issue you're bringing up is named vs default exports. There isn't much difference in these other than how the import works, but the big thing to recognize is that with a named export (export class <ClassName>) you must import that class in another file with the same name (though you are able to give it an alias using as). With default exports you can export anything as default once per file, but you can import it into another file with any name. So if you wanted you could have export default MyClass and then have import SomethingNotRelatedToTheName from path/to/MyClass.

If you feel strongly about it, you can always rewrite and rename your filenames and exports, but don't expect Nest to change that for you, as it is an opinionated framework.

Related