javascriptrequirejscommonjs

Import file based on relative path in JavaScript


I have such project structure:

- MyApp
`- firstFolder
 `- firstFile.js
`- secondFolder
 `- thirdFolder
  `- thirdFile.js

How can I import firstFile.js from thirdFile.js?

Something like import myFunc from '../firstFolder/firstFile'; in thirdFile.js, doesn't work.


Solution

  • Description

    There are multiple pathing options, I'll describe a couple below.

    Folder Structure

    MyApp
    ├── firstFolder
    │   └── firstFile.js
    └── secondFolder
        └── thirdFolder
            └── thirdFile.js
    

    Relative path

    Here we will import the firstFile from our thirdFile.

    ../ will go back 1 folder, this is why we go back two folders:

    import myFunc from '../../firstFolder/firstFile'
    

    So .. takes us back to secondFolder then we need to go back one more folder .. into the MyApp folder. Now we can traverse forward into firstFolder then point to firstFile.

    or ./ - this is the present working directory (pwd), which will be thirdFolder from here we will need to go back 2 directories or ../..

    import myFunc from './../../firstFolder/firstFile'
    

    Full path

    Since you didn't specify the full paths these are incomplete

    / - will start at the root directory of the Operating System

    import myFunc from '/fullPathtoProject/MyApp/firstFolder/firstFile'
    

    ~/ this is the current users home directory

    import myFunc from '~/pathFromHomeDirectory/MyApp/firstFolder/firstFile'