我有这样的项目结构:
- MyApp
`- firstFolder
`- firstFile.js
`- secondFolder
`- thirdFolder
`- thirdFile.js
如何从
firstFile.js
导入 thirdFile.js
?
类似
import myFunc from '../firstFolder/firstFile';
中的 thirdFile.js
的东西不起作用。
有多种路径选项,我将在下面描述其中几个。
MyApp
├── firstFolder
│ └── firstFile.js
└── secondFolder
└── thirdFolder
└── thirdFile.js
在这里,我们将
import
来自我们的 firstFile
的 thirdFile
。
../
将返回 1 个文件夹,这就是我们返回两个文件夹的原因:
import myFunc from ../../firstFolder/firstFile
所以
..
带我们回到secondFolder
,然后我们需要再返回一个文件夹..
到MyApp
文件夹中。现在我们可以向前遍历到 firstFolder
然后指向 firstFile
。
或
./
- 这是当前的工作目录(pwd),从这里开始我们将需要返回 2 个目录或 thirdFolder
../..
完整路径由于您没有指定完整路径,因此这些路径不完整
import myFunc from ./../../firstFolder/firstFile
- 将从操作系统的根目录启动
/
import myFunc from /fullPathtoProject/MyApp/firstFolder/firstFile
这是当前用户的主目录
~/
您应该使用两个“..”来返回 1 级文件夹
import myFunc from ~/pathFromHomeDirectory/MyApp/firstFolder/firstFile
ES6(ecmascript6):
var myFunc = require('../../firstFolder/firstFile');
import myFunc from '../../firstFolder/firstFile';
或
import myFunc from '../../firstFolder/firstFile';
import * as myFunc from '../../firstFolder/firstFile';
更改为这个
webpack.config.js
或者,如果您的来源均与
resolve: {
modules: [
path.resolve('./'),
path.resolve('./node_modules')
]
},
有关,请使用
./src
。如果您想更具体,您还可以查看 path.resolve('./src')
(请参阅此处的 webpack 文档:https://webpack.js.org/configuration/resolve/) 顺便说一句:我在我的应用程序中使用 next.js,它有自己的 webpack 配置,但如果你输入类似的内容,你可以修改它
resolve.alias
进入您的
const path = require('path');
module.exports = ({
webpack: (config, options) => {
config.resolve.modules.push( path.resolve('./') )
return config
},
})
,以修改默认值。