【Exception】Error: Dynamic require of “path“ is not supported

Talk is cheap, show me the code.

环境 | Environment

kversion
OSwindows 11
Node.jsv18.14.2
npm9.5.0
vite5.0.0
vue3.3.8

报错日志 | Error log

>npm run dev

> app1@0.0.0 dev
> vite


 ERROR  failed to load config from C:\code\frontend\app1\vite.config.js                22:01:42  


 ERROR  error when starting dev server:                                                                                    22:01:42  
Error: Dynamic require of "path" is not supported
    at file:///C:/code/frontend/app1/vite.config.js.timestamp-1700661702409-1225e92edb929.mjs:6:9    at file:///C:/code/frontend/app1/vite.config.js.timestamp-1700661702409-1225e92edb929.mjs:14:12
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

vite.config.js

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'

const path = require('path')

// 为了在index.html中使用环境变量
const getViteEnv = (mode, target) => {
  return loadEnv(mode, process.cwd())[target];
};

// https://vitejs.dev/config/
export default ({ mode }) =>
  defineConfig({
    plugins: [
      vue(),
      createHtmlPlugin({
        inject: {
          data: {
            //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
            title: getViteEnv(mode, "VITE_APP_TITLE"),
          },
        },
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, "./src")
      }
    },
  })

原因分析 | Analysis

  1. VITE v5.0.0不支持require()

解决方案 | Solution

const path = require('path')改为import path from 'path'

参考 | References

简书 - vite项目中出现的错误Error: Dynamic require of “path” is not supported

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值