Vue编译出现This file is being treated as an ES module because it has a '.js' file extension错误
  TEZNKK3IfmPf 21天前 10 0
vue

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

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"
]}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 21天前 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年03月30日   49   0   0 vue
  TEZNKK3IfmPf   28天前   18   0   0 vue
  I7JaHrFMuDsU   2024年03月22日   20   0   0 javascriptvue
  TEZNKK3IfmPf   2024年03月29日   30   0   0 javascriptvue
TEZNKK3IfmPf