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> app1@0.0.0 dev
> viteERROR 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 supportedat 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:12at 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
VITE v5.0.0
不支持require()
解決方案 | Solution
將const path = require('path')
改為import path from 'path'
參考 | References
簡書 - vite項目中出現的錯誤Error: Dynamic require of “path” is not supported