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.
Relative path Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory.
A link that has an absolute path will tell the computer which server to go to and then all the folders that you have to drill down through to get to the target. A link that has a relative path will be written to tell the computer how to get from the folder with the currently viewed topic to the target.
The import path is a list of locations that may name file system paths or zip files.
A relative path needs to be combined with another path in order to access a file. For example, joe/foo is a relative path.
Here are the pathing options:
../
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
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
If you use webpack you can tweak the loader to search for files relative to your base directory. Change your webpack.config.js
to this
resolve: {
modules: [
path.resolve('./'),
path.resolve('./node_modules')
]
},
or, if your sources are all relative to ./src
, use path.resolve('./src')
. If you want to be more specific you can also take a look at resolve.alias
(see the webpack docs here: https://webpack.js.org/configuration/resolve/)
BTW: I'm using next.js in my application, which has its own webpack config, but you can modify it if you put something like
const path = require('path');
module.exports = ({
webpack: (config, options) => {
config.resolve.modules.push( path.resolve('./') )
return config
},
})
into your next.config.js
, in order to modify the default one.
use=>
import myFunc from '../../firstFolder/firstFile';
or
import * as myFunc from '../../firstFolder/firstFile';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With