node.jstypescriptnestjses6-modulesesmodules

Import `path` for Node reacts differently in NestJS


I have a NestJS application with some commands attached to it. When I run the application I can import path as

import path from 'path';

and it will work fine.

When I use nest-command to run a CLI command, I get an error

Cannot read properties of undefined (reading 'join')

obviously referring to the path.join function

If I change it to

import * as path from 'path'

It works fine on the command but not in the main application!

What is the problem?


Solution

  • this has nothing to do with NestJS. This is due to how TypeScript works depending on your typescript compiler configuration (usually tsconfig.json file)

    You can use import path from "node:path" if you have the esModuleInterop on. Otherwise (the default), you'll have to use import * as path from "node:path"

    Read the typescript docs: