我的项目结构如下:
- MyApp
`- firstFolder
`- firstFile.js
`- secondFolder
`- thirdFolder
`- thirdFile.js
我该如何从thirdFile.js
中导入firstFile.js
?
像在thirdFile.js
中使用import myFunc from '../firstFolder/firstFile';
这样的语句并不能起作用。
我的项目结构如下:
- MyApp
`- firstFolder
`- firstFile.js
`- secondFolder
`- thirdFolder
`- thirdFile.js
我该如何从thirdFile.js
中导入firstFile.js
?
像在thirdFile.js
中使用import myFunc from '../firstFolder/firstFile';
这样的语句并不能起作用。
这里是路径选项(相对路径):
../
会回到上一级文件夹,所以我们需要回到两个文件夹:
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
/
而不是 ./
,这是一个 Node.js 的引用。 - abc123../
,可以试试 ~/
,你只是用这些作为第一个字符吗?能否发布完整的字符串? - abc123import myFunc from ./firstFolder/firstFile.js
是错误的。单个 .
表示当前目录。 - Matt Yoon在 ES5 中:
你应该使用两个 '..' 来返回上一级文件夹。
var myFunc = require('../../firstFolder/firstFile');
ES6(ECMAScript 6):
import myFunc from '../../firstFolder/firstFile';
webpack.config.js
更改为如下:resolve: {
modules: [
path.resolve('./'),
path.resolve('./node_modules')
]
},
./src
,可以使用path.resolve('./src')
。如果你想更具体地指定路径,可以查看resolve.alias
(在这里查看webpack文档:https://webpack.js.org/configuration/resolve/)。const path = require('path');
module.exports = ({
webpack: (config, options) => {
config.resolve.modules.push( path.resolve('./') )
return config
},
})
next.config.js
中,以修改默认配置。use=>
import myFunc from '../../firstFolder/firstFile';
或者
import * as myFunc from '../../firstFolder/firstFile';
import ../../firstFolder/firstFile.js;
orimport ./firstFolder/firstFile.js
- abc123