Vue编译出现This file is being treated as an ES module because it has a '.js' file extension错误

发布时间 2023-09-12 22:37:50作者: 卡洛小豆

问题描述

在编译前端项目时出现下面的问题:

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.exportsrequire关键字,如下所示

module.exports = {
  plugins: [require("tailwindcss"), require("autoprefixer")],
};

在默认使用vite创建的项目中,package.json文件中有一个配置为 "type": "module",这时对应ECMAScript的语法规范,会使用ES Module模块的方式处理代码,对应的关键词为exportimport,代码如下所示:

export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {}
  }
}

packpage.json中定义的方式与代码不符时,就会出现编译错误的情况。

解决方案

1、修改代码,使用与模块编译时对应的关键词

2、默认使用CommonJS的规范时,使用mjs为后缀定义使用ES Module的文件,或者在packpage.json中定义typemodule或使用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"
]}