[英]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
?如何导入
firstFile.js
从thirdFile.js
?
Something like import myFunc from '../firstFolder/firstFile';
类似于
import myFunc from '../firstFolder/firstFile';
in thirdFile.js
, doesn't work.在
thirdFile.js
,不起作用。
../ will go back 1 folder, this is why we go back two folders: ../ 将返回 1 个文件夹,这就是我们返回两个文件夹的原因:
import myFunc from ../../firstFolder/firstFile.js;
or these will start at the root directory或者这些将从根目录开始
import myFunc from /firstFolder/firstFile.js
import myFunc from ./firstFolder/firstFile.js
import myFunc from ~/firstFolder/firstFile.js
use=>使用=>
import myFunc from '../../firstFolder/firstFile';
or或者
import * as myFunc from '../../firstFolder/firstFile';
in ES5:在 ES5 中:
You should use two '..' to back 1 folder level您应该使用两个“..”来支持 1 个文件夹级别
var myFunc = require('../../firstFolder/firstFile');
ES6 (ecmascript6): ES6 (ecmascript6):
import myFunc from '../../firstFolder/firstFile';
If you use webpack you can tweak the loader to search for files relative to your base directory.如果你使用 webpack,你可以调整加载器来搜索相对于你的基本目录的文件。 Change your
webpack.config.js
to this将您的
webpack.config.js
更改为此
resolve: {
modules: [
path.resolve('./'),
path.resolve('./node_modules')
]
},
or, if your sources are all relative to ./src
, use path.resolve('./src')
.或者,如果您的来源都与
./src
,请使用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/ )如果您想更具体一些,你也可以看看
resolve.alias
(看到这里的文档的WebPack: 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顺便说一句:我在我的应用程序中使用 next.js,它有自己的 webpack 配置,但如果你把它像
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.进入你的
next.config.js
,以修改默认的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.