import attributes 是标准写法,关键字为 with:静态导入用 import x from 'y' with { type: 'css/json' },动态导入用 await import('y', { with: { type: 'css/json' } });css 需手动挂载到 adoptedstylesheets,json 返回 { default: ... } 结构且需服务端正确 mime 类型。

在模块脚本中直接引入 CSS 或 JSON 这类非 JavaScript 资源,过去只能靠构建工具“模拟”或手动 fetch,现在浏览器原生支持了——但必须用对语法,否则会静默失败或报错。
Import Attributes 是标准写法,不是 assert
TC39 提案已正式定名 Import Attributes,关键字是 with,不是旧版的 assert。所有新项目应使用现行语法:
- 静态导入 CSS:
import sheet from './theme.css' with { type: 'css' }; - 静态导入 JSON:
import data from './config.json' with { type: 'json' }; - 动态导入(更常用):
const { default: styles } = await import('./theme.css', { with: { type: 'css' } });
写 assert 会被现代浏览器忽略,退化为普通 JS 模块加载,大概率报错。
使用 JSON Schema 验证 JSON 数据,从示例 JSON 生成 schema,并将其转换为 TypeScript 接口、Python 数据类或 Markdown 文档。
CSS 导入后要手动挂载才生效
导入返回的是 CSSStyleSheet 实例,不是字符串,也不自动插入文档:
- 不能当 URL 用,也不能直接
console.log(sheet)看内容(它没有.toString()) - 要让样式生效,必须显式挂载:
document.adoptedStyleSheets = [sheet]; - 若用于 Shadow DOM,写成
shadowRoot.adoptedStyleSheets = [sheet]; - 不支持变量路径,
import from `./${theme}.css`会语法报错
JSON 导入只支持动态方式,且结构固定
静态 import ... with { type: 'json' } 在部分浏览器(如 Chrome 125+)已支持,但兼容性仍弱;生产环境推荐统一用动态导入:
const { default: config } = await import('./config.json', { with: { type: 'json' } });- 返回对象一定是
{ default: {...} }形式,必须解构取default - 服务端响应头必须是
Content-Type: application/json,否则断言失败 - 文件内容需严格符合 JSON 格式:无注释、无尾逗号、键名必须双引号
不适用时,该换方案
Import Attributes 不是万能钥匙,遇到这些情况建议绕开:
- 需要兼容 Safari ≤15.4 或旧版 Edge —— 改用
fetch('./config.json').then(r => r.json()) - JSON 数据需运行时校验字段 —— 先导入再用 Zod / Yup 做类型守卫
- CSS 需媒体查询条件加载或
load事件监听 —— 回退到<link rel="stylesheet"> - 开发环境用 Vite/Webpack —— 它们对
.json的静态 import 是打包时处理的,和浏览器原生能力无关










