为什么需要导入断言
导入断言(Import Assertions)允许在导入时声明模块内容的类型,确保加载的模块符合预期格式。
一、静态导入断言
1.1 导入 JSON
// 旧语法:使用 assert
import data from './data.json' assert { type: 'json' };
// 新语法:使用 with(ES2022+)
import data from './data.json' with { type: 'json' };
console.log(data);
1.2 断言 vs attribute
assert是旧语法(Stage 3)with是新语法(ES2022+),已稳定
// 推荐使用 with
import config from './config.json' with { type: 'json' };
二、动态导入断言
2.1 动态导入 JSON
// 使用 assert
const data = await import('./data.json', { assert: { type: 'json' } });
// 使用 with
const data = await import('./data.json', { with: { type: 'json' } });
2.2 断言失败
如果导入的资源类型与断言不符,会抛出错误:
try {
await import('./data.txt', { with: { type: 'json' } });
} catch (e) {
console.error('Import failed:', e.message);
}
三、Web 标准
3.1 支持的类型
目前支持 type: 'json',未来可能扩展:
import styles from './styles.css' with { type: 'css' };
import wasm from './module.wasm' with { type: 'webassembly' };
3.2 CSS 模块
某些构建工具支持 CSS 模块加载:
import styles from './component.module.css' with { type: 'css' };
document.adoptedStyleSheets = [styles];
四、与 dynamic import 的关系
4.1 导入断言 vs 导入条件
导入断言声明模块的内容类型,导入条件根据环境选择不同模块:
// 导入断言
import data from './data.json' with { type: 'json' };
// 导入条件(ES2022+)
import data from './data.json' with { type: 'json' };
4.2 常见用途
// 加载配置文件
const config = await import('./config.json', { with: { type: 'json' } });
// 加载 WebAssembly
const wasm = await import('./module.wasm', { with: { type: 'webassembly' } });