前言(报错思考🤔)
1、建个文件夹
npm init 一下。
接着创俩文件,一个是module.js,一个是index.js,
记得package.json要加个type: 'module'。至于加这个的原因是:Node.js 正在尝试加载一个 ES 模块(ESM),但当前环境没有正确配置为支持 ES 模块。Node.js 默认将 JavaScript 文件视为 CommonJS 模块(CJS),而不是 ES 模块。
在 package.json 中设置 "type": "module",就是告诉Node.js 你正在使用 ES 模块。
注意:
- 如果使用这种方法,所有
.js文件都会被当作 ES 模块处理。 - 如果某些文件需要使用 CommonJS 语法(如
require),你需要将它们的扩展名改为.cjs。
另外俩文件的代码示例如下:
// module.js
export const utils = {
math: {
add: (a, b) => a + b,
},
text: {
capitalize: (str) => str.charAt(0).toUpperCase() + str.slice(1),
},
};
// index.js
import { utils: { math, text } } from "./module.js"; // 这种写法出现报错
math.add(1, 2);
text.capitalize('hello');
import { utils: { math, text } } from "./module.js";
是不合法的语法,因此会抛出 SyntaxError: Unexpected token ':' 错误。
正文(解决方法)
如果你想要解构嵌套的对象,可以分两步进行:
方法 1:先导入 utils,再解构
import { utils } from "./module.js";
// 解构 utils 中的 math 和 text
const { math, text } = utils;
// 直接使用
math.add(1, 2);
text.capitalize('hello');
方法 2:直接导入嵌套的属性
如果 module.js 中导出了 math 和 text 作为独立的命名导出,你可以直接导入它们:
import { math, text } from "./module.js";
// 直接使用
math.add(1, 2);
text.capitalize('hello');
为什么不能直接在 import 中嵌套解构?
JavaScript 的 import 语法设计上只支持简单的解构,例如:
import { a, b, c } from "./module.js";
但不支持嵌套解构,例如:
import { a: { b, c } } from "./module.js"; // 错误
这是因为 import 语句的语法解析器不支持这种复杂的解构形式。如果你需要解构嵌套的对象,必须在导入后再进行解构。
示例代码
假设 module.js 的内容如下:
export const utils = {
math: {
add: (a, b) => a + b,
},
text: {
capitalize: (str) => str.charAt(0).toUpperCase() + str.slice(1),
},
};
你可以这样导入并使用:
import { utils } from "./module.js";
// 解构 utils 中的 math 和 text
const { math, text } = utils;
// 直接使用
console.log(math.add(1, 2)); // 输出: 3
console.log(text.capitalize('hello')); // 输出: Hello
总结(提升+点题🌞)
- 不能在
import语句中直接嵌套解构。 - 如果需要解构嵌套的对象,可以先导入整个对象,然后在代码中进行解构。
- 如果嵌套的属性是独立的命名导出,可以直接导入它们。