You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于commitlint配置兼容package.json type:module的问题咨询

解决commitlint配置兼容CommonJS与ES模块环境的问题

我开发了一个集成commitlint、release-it的开源项目启动模板。当用户克隆项目后,若在package.json中添加"type": "module"并执行提交操作:

git add package.json 
git commit -m "fail"

本该触发commitlint的规范校验提示,实际却抛出错误:

ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/oleersoy/Github/RM1/fs-github-flow-docs-starter/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///Users/oleersoy/Github/RM1/fs-github-flow-docs-starter/commitlint.config.js:1:1
    ...

原因是当package.json设置"type": "module"时,Node会将.js文件视为ES模块,而原commitlint配置采用CommonJS的module.exports语法,导致报错。若改为ES模块格式的配置:

const Configuration = { extends: ['@commitlint/config-conventional'] };
export default Configuration;

在未设置"type": "module"的项目中又会抛出语法错误:

SyntaxError: Unexpected token 'export'
    at wrapSafe (node:internal/modules/cjs/loader:1281:20)
    ...

以下是几种不受package.json中"type": "module"属性影响的commitlint配置方案,能让模板使用者无需修改配置即可避免报错:

方案1:使用.cjs后缀命名配置文件

将原commitlint.config.js重命名为commitlint.config.cjs,配置内容保留CommonJS格式:

module.exports = {
  extends: ['@commitlint/config-conventional']
};

Node会强制将.cjs后缀的文件当作CommonJS模块处理,无论项目是否开启ES模块模式,commitlint都能正确加载配置。适合需要编写带逻辑的复杂配置场景。

方案2:采用JSON格式配置文件

创建commitlint.config.json文件,内容如下:

{
  "extends": ["@commitlint/config-conventional"]
}

JSON格式的配置文件不受模块系统限制,CommonJS和ES模块环境下都能被commitlint正常识别,配置简洁直观。

方案3:在package.json中内置commitlint配置

直接在项目的package.json中添加commitlint字段,无需额外配置文件:

{
  // ...项目其他配置
  "commitlint": {
    "extends": ["@commitlint/config-conventional"]
  }
}

commitlint会自动读取package.json中的配置,完全规避模块类型冲突问题,对开发者最友好。

内容的提问来源于stack exchange,提问作者Ole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 02:57:20