Node.js + Webpack + TypeScript: dirname returns the root of the C drive
There is a library that is being developed along the way, and the main project that uses this library. Admit:
- The library has a file
library.ts
, its absolute path isС:\Users\user1\projects\lib1\src\library.ts
- The project that uses the library has a file
someProject.ts
whose absolute path isC:\Users\user1\projects\someProject\src\someProject.ts
The library is written in TypeScript and is built by Webpack in JavaScript for execution in the environment Node.js.
You need to programmatically get the path С:\Users\user1\projects\lib1\src
in the file library.ts
. I have already solved this problem in one way-via DefinePlugin
, but I don't like that in library.ts
, __dirname
returns only /
. Because of this, path.resolve(__dirname, 'fileName')
will give C:\fileName
.
Naturally, I run the project NOT in the root of the C:
1 answers
To manage special node variables, webpack has a special configuration in the config:
node: {
__dirname: ...,
}
As written in the documentation, for __dirname
there are three options:
-
"mock"
(default) - always use"/"; -
true
- the relative path to the directory where the source file is located is used (the path is taken relative to the settingcontext
); -
false
- the path to the directory where the output file is located is used (actually, webpack does not touch this variable at all, and it is handled by the node-so this option will not work in the browser).
Choose the option that suits you.