Why webpack config has to use path.resolve & path.join

后端 未结 1 972
猫巷女王i
猫巷女王i 2021-02-08 23:43

It is common seen in webpack configuration that when we need to set the path ,path.resolve or path.join are often use

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-09 00:29

    This has nothing to do with webpack, only with the way Node.js handles paths. Paths are not resolved relative to the file path, but relative to the working directory by default. Say we have the following directory structure:

    project
     ├── a
     |   └── 1.js
     └── b
         └── 2.txt
    

    with 1.js containing the following:

    const filePath = '../b/2.txt';
    const content = require('fs').readFileSync(filePath);
    console.log(content.toString());
    

    then, if we run

    cd a
    node 1.js
    

    everything works fine.

    But if, instead we execute from the toplevel directory, the following:

    node a/1.js
    

    we get an error:

    Error: ENOENT: no such file or directory, open 'C:\Users\baryl\Desktop\b\2.txt'
    

    because the path is now resolved relative to project instead of project/a. path.resolve solves that.

    const path = require('path');
    const filePath = path.resolve(__dirname, '../b/2.txt');
    const content = require('fs').readFileSync(filePath);
    console.log(content.toString());
    

    now we can safely execute node a/1.js from the project directory, and it will work as expected.

    0 讨论(0)
提交回复
热议问题