【bug修复系列】package.json中“type”: “module”的作用,解决明明是ES module却报是CommonJS的问题

文章目录

一、问题描述

vite中,可以使用vite-plugin-static-copy工具将文件拷贝到指定的dist目录。

于是我开始构建:

bash 复制代码
npm run build

发现报错:

js 复制代码
failed to load config from D:\AIProject\translationChrome\vite.config.js
error during build:
Error [ERR_REQUIRE_ESM]: require() of ES Module D:\AIProject\translationChrome\node_modules\vite-plugin-static-copy\dist\index.js from D:\AIProject\translationChrome\vite.config.js not supported.
Instead change the require of index.js in D:\AIProject\translationChrome\vite.config.js to a dynamic import() which is available in all CommonJS modules.
    at _require.extensions.<computed> [as .js] (file:///D:/AIProject/translationChrome/node_modules/vite/dist/node/chunks/dep-BJP6rrE_.js:53946:9)
    at Object.<anonymous> (D:\AIProject\translationChrome\vite.config.js:37:38)

大意是因为 vite-plugin-static-copy 是一个 ES 模块,而我的 vite.config.js 使用的是 CommonJS 模块格式(require),这两者存在不兼容问题。Vite 配置文件默认是 ESM(ES Modules)格式,所以需要使用 import 而不是 require

二、问题解决

我确认了下vite.config.js中引入vite-plugin-static-copy确实是用import的方式的。

bash 复制代码
import { viteStaticCopy } from 'vite-plugin-static-copy';

按道理,不会有这种问题,因为其他模块也是这样,但是没有报错。

经过网上搜索和将问题丢给AI诊断,终于发现原来是我的package.json中没有配置 "type": "module",这个选项导致。

之前项目中有这个,只是没留意,那它的作用是什么:

When set to "module", the type field allows a package to specify all .js files within are ES modules. If the "type" field is omitted or set to "commonjs", all .js files are treated as CommonJS.

翻译过来的意思是:

当设置 "type": "module",时,允许package 中的所有的.js模块当做ES modules,但是如果该配置缺失或者设置为了"commonjs",那么就会当做CommonJS模块来处理。

而我的问题恰好是因为没有设置的原因,导致在构建时,当做了CommonJS来处理,从而报错。

所以,解决问题的方式就是在项目根目录下的package.json添加一行配置:

json 复制代码
{
    "type": "module", //加这一行
    "name": "translation",
  	"version": "1.0.0",
  	"description": ""
}

要不是遇到了这个问题,还真没留意到"type": "module",的作用。特此笔记记录。


如果你在web前端开发、面试、前端学习路线有困难可以在下方加我名片。

免费答疑,行业深潜多年的技术牛人帮你解决bug。

并可提供web前端开发,网站开发、技术咨询、答疑、直播讲座等服务。

祝你能成为一名优秀的WEB前端开发工程师!

相关推荐
前网易架构师-高司机10 小时前
带标注的羽毛球运动员,裁判,羽毛球识别数据集,识别率84.4%,2879张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·羽毛球·裁判
leisoo809712 小时前
股票数据本地化存储实战:JSON、数据库与列式存储的方案对比
jvm·数据库·json
切糕师学AI12 小时前
从压缩到查询:PostgreSQL中JSON数据的存储与处理实践
数据库·postgresql·json
倾听醉梦语14 小时前
React/Vite/Next.js 前端开发工具 SpotPatch:点击页面元素精准定位 JSX/TSX 源码
javascript·react·ai编程·vite·next.js·前端开发工具
doubt。16 小时前
大模型prompt工程Zero-Shot与Few-Shot以及json格式
人工智能·深度学习·机器学习·语言模型·json·prompt
吨吨ai17 小时前
# ChatGPT Plus / Pro + Codex Debug 实战:如何让 AI 从日志、Trace、异常堆栈自动定位线上 Bug
人工智能·chatgpt·bug
灰暗世界%1 天前
飞牛bug修复
bug
烟锁池塘柳02 天前
Conda 创建环境报错:Unable to read repodata JSON file,清华源 pkgs/free 失效解决方法
json·conda
云水一下2 天前
零基础玩转bWAPP靶场(四十五):XSS - Reflected (JSON)
web安全·json·xss·bwapp·reflected
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ3 天前
Spring‑AI Document 对象 JSON 字段详解
人工智能·spring·json