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

Talk is cheap, show me the code.

环境 | Environment

k version
OS windows 11
Node.js v18.14.2
npm 9.5.0
vite 5.0.0
vue 3.3.8

报错日志 | Error log

>npm run dev

> [email protected] 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

你可能感兴趣的:(Exception,VUE系列,npm,vite,前端)