JavaScript中如何基于相对路径导入文件

24

我的项目结构如下:

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

我该如何从thirdFile.js中导入firstFile.js

像在thirdFile.js中使用import myFunc from '../firstFolder/firstFile';这样的语句并不能起作用。


import ../../firstFolder/firstFile.js; or import ./firstFolder/firstFile.js - abc123
你尝试过'../../firstFolder/firstFile'吗?因为你需要向上两个目录。 - Shilly
1
@abc123 第二个答案不起作用。 - Yurii N.
请参阅https://levelup.gitconnected.com/understand-and-configure-absolute-import-paths-in-javascript-5cde3be2630d,了解如何理解和配置JavaScript中的绝对导入路径。 - Michael Freidgeim
4个回答

19

Description

这里是路径选项(相对路径):

../ 会回到上一级文件夹,所以我们需要回到两个文件夹:

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

所以 .. 带我们回到 secondFolder,然后我们需要返回一个更高的文件夹 ..MyApp 文件夹。现在我们可以前进到 firstFolder 然后指向 firstFile

或者使用 ./ - 这是当前工作目录(pwd),从这里将是 thirdFolder,我们需要返回两个目录或 ../..

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

其他目录路径选项(完整路径):

由于您没有指定完整路径,因此这些路径是不完整的。

/ - 将从操作系统的根目录开始。

import myFunc from /fullPathtoProject/MyApp/firstFolder/firstFile

~/ 表示当前用户的主目录

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

@YuriyN,请尝试使用 / 而不是 ./,这是一个 Node.js 的引用。 - abc123
1
@YuriyN. k,那你需要使用 ../,可以试试 ~/,你只是用这些作为第一个字符吗?能否发布完整的字符串? - abc123
什么都不起作用,我尝试了所有这些情况,但它不起作用。 - Yurii N.
2
示例 import myFunc from ./firstFolder/firstFile.js 是错误的。单个 . 表示当前目录。 - Matt Yoon
只使用斜杠前缀而不是“./”对我来说在现代浏览器中有效。波浪线变体则不行。因此,我认为这个答案连同之前的评论一起存在太多错误,不能在这里。 - matanster
显示剩余4条评论

3

在 ES5 中:

你应该使用两个 '..' 来返回上一级文件夹。

var myFunc = require('../../firstFolder/firstFile');

ES6(ECMAScript 6):

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

谢谢回答!但是abc123先回答了它。 - Yurii N.

2
如果你使用webpack,你可以调整加载器来相对于你的基本目录搜索文件。将你的webpack.config.js更改为如下:
resolve: {
  modules: [
    path.resolve('./'),
    path.resolve('./node_modules')
  ]
},

或者,如果你的资源都相对于./src,可以使用path.resolve('./src')。如果你想更具体地指定路径,可以查看resolve.alias(在这里查看webpack文档:https://webpack.js.org/configuration/resolve/)。
顺便说一句:我在我的应用程序中使用next.js,它有自己的webpack配置,但是如果你放置类似于以下内容的东西,你可以修改它。
const path = require('path');
module.exports = ({
    webpack: (config, options) => {
        config.resolve.modules.push( path.resolve('./') )
        return config
    },
})

将以下代码添加到next.config.js中,以修改默认配置。

2

use=>

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

或者

import * as myFunc from '../../firstFolder/firstFile';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接