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 卡洛小豆
【转载文章务必保留出处和署名,谢谢!】

浙公网安备 33010602011771号