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

Vue项目中module未定义报错:原因分析及解决方法

问题原因与解决方法

问题原因

  1. 模块规范不匹配:Vue 3 + Vite初始化的项目默认采用**ES模块(ESM)**规范,项目中.js后缀的文件会被Node当作ESM处理,而module.exports是CommonJS(CJS)的导出语法,在ESM环境中无法被识别,导致语法不生效。
  2. ESLint环境配置缺失:ESLint默认没有为tailwind.config.js配置Node环境,因此会提示module变量未定义——因为浏览器/纯ESM环境中不存在module这个全局变量。

解决方法

方法1:将配置文件改为CommonJS后缀

把tailwind.config.js重命名为tailwind.config.cjs,Node会自动将其识别为CommonJS文件,module.exports语法就能正常生效。同时在文件顶部添加注释,彻底消除ESLint的环境提示:

/* eslint-env node */
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

方法2:改用ES模块语法编写配置

保持tailwind.config.js后缀不变,将module.exports替换为ESM的export default,贴合项目默认的模块规范:

/* eslint-env node */
/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

方法3:全局配置ESLint识别Node环境(可选)

如果不想修改单个文件,可在项目的.eslintrc.cjs中全局添加Node环境配置,让ESLint对所有配置文件生效:

/* eslint-env node */
require("@rushstack/eslint-patch/modern-module-resolution");

module.exports = {
  root: true,
  env: {
    node: true // 全局启用Node环境
  },
  extends: [
    "plugin:vue/vue3-essential",
    "eslint:recommended",
    "@vue/eslint-config-prettier",
  ],
  parserOptions: {
    ecmaVersion: "latest",
  },
};

注意:该方法仅解决ESLint的module未定义提示,无法修复module.exports在ESM文件中不生效的问题,需配合方法1或2使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:48:59