目录结构
main.js
import { Name, say, Person } from './test'
console.log(Name)
test.js
const Name = 'life'
function say() {
console.log('Mine')
}
let Person = { name: `good` }
export { Name, say, Person }
问题分析
步骤有点啰嗦,犯错的原因其实就很简单,就是没有把要导入的文件名写全,所有就报如下没有找到对应文件的错误。
Error [ERR_MODULE_NOT_FOUND]: Cannot find module ‘d:\Project_Files\VSCode_Projects\React_Learning\《React全栈》\第1章\ES6语言特性\e7_Modules\test’ imported from d:\Project_Files\VSCode_Projects\React_Learning\《React全栈》\第1章\ES6语言特性\e7_Modules\main.js
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:416:11)
at moduleResolve (node:internal/modules/esm/resolve:932:10)
at defaultResolve (node:internal/modules/esm/resolve:1044:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
at ModuleWrap. (node:internal/modules/esm/module_job:76:40)
at link (node:internal/modules/esm/module_job:75:36) {
code: ‘ERR_MODULE_NOT_FOUND’
}
需求
想要在main.js
文件下导入test.js
文件导出的模块对象与变量
解决问题
在VSCode的右键到对应的终端
到终端输入命令npm init -y
新建package.json
文件
加入 “type”:“modules”
修改导入的文件名
main.js
最终输出结果为: