I'm following a nest tutorial and the instructor creates a folder called dtos and inside it creates two dto's (create-user.dto and edit-user.dto). Then, create an index file (in the same folder) that contains only the following:
index.ts:
export * from './create-user.dto';
export * from './edit-user.dto'
I don't understand two things:
1-why do you export the dtos from there? they already export themselves.
2- because it uses exports the dtos directly. Shouldn't I import them first?
Here is the code of the data: edit-user.dto:
export class EditUserDto {}
create-user.dto:
export class CreateUserDto {}
CodePudding user response:
1-why do you export the dtos from there? they already export themselves.
It allows for more concise importing. Say your folder structure is:
top
index
dtos
index
create-user
edit-user
If you import create-user and edit-user into dtos/index, and then export them from dtos/index, you can then import them from the top index with:
import { EditUserDto, CreateUserDto } from './dtos';
This is accessing what dtos/index
exports.
Without this - yes, the classes are already exported, but importing them elsewhere takes a few more characters, since you have to navigate the folder structure more. From the top's index, you'd need:
import { EditUserDto } from './dtos/edit-user.dto';
import { CreaetUserDto } from './dtos/create-user.dto';
It's ever so slightly more unwieldy. Not a big deal. Some might prefer the extra boilerplate in order to import more concisely, others might prefer to navigate directly to the nested file location without bothering. Either will work just fine.
2- because it uses exports the dtos directly. Shouldn't I import them first?
You can import from a file and export that which you're importing in the same line using that syntax you see. export * from 'path'
will take everything path
exports, and export it in the current file as well.