Vue编译出现This file is being treated as an ES module because it has a '.js' file extension错误
问题描述
在编译前端项目时出现下面的问题:
Failed to load PostCSS config: Failed to load PostCSS config (searchPath: D:/WebProject/imooc-front): [Failed to load PostCSS config] Failed to load PostCSS config (searchPath: D:/WebProject/imooc-front):This file is being treated as an ES module because it has a '.js' file extension and 'D:\WebProject\imooc-front\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
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 'D:\WebProject\imooc-front\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///D:/WebProject/imooc-front/postcss.config.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
环境
- node : 18.17.1
- vue : 3.3.4
- vite : 4.4.5
原因
NodeJS
默认以CommonJS
的规范来执行JavaScript代码,使用CommonJS
模块的导出和导入方式,也就是对应代码中的module.exports
和require
关键字,如下所示
module.exports = {
plugins: [require("tailwindcss"), require("autoprefixer")],
};
在默认使用vite创建的项目中,package.json
文件中有一个配置为 "type": "module"
,这时对应ECMAScript
的语法规范,会使用ES Module
模块的方式处理代码,对应的关键词为export
和import
,代码如下所示:
export default {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
}
在packpage.json
中定义的方式与代码不符时,就会出现编译错误的情况。
解决方案
1、修改代码,使用与模块编译时对应的关键词
2、默认使用CommonJS的规范时,使用mjs
为后缀定义使用ES Module
的文件,或者在packpage.json
中定义type
为module
或使用cjs
为后缀定义使用CommonJS
规范的文件
3、当代码中有两种规范混用的时候,可以使用babel
安装babel相关的依赖:
npm install --save-dev babel-core babel-loader babel-preset-env babel-preset-stage-3
在安装完依赖之后,我们需要在项目根目录下创建一个.babelrc文件,这个文件将会用来指定babel的配置。
{
"presets": [
["env", {"modules": false}],
"stage-3"
]}
GitHub : https://github.com/fxiaoyu97
博客园 : https://www.cnblogs.com/tudou1179006580
微信公众号 : 三更编程菌
Copyright ©2019 卡洛小豆
【转载文章务必保留出处和署名,谢谢!】
博客园 : https://www.cnblogs.com/tudou1179006580
微信公众号 : 三更编程菌
Copyright ©2019 卡洛小豆
【转载文章务必保留出处和署名,谢谢!】
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具