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

如何构建可通过Python http.server部署的Vue 3(Vite)项目?

解决Vue 3(Vite)项目无法用python -m http.server部署的MIME类型问题

问题核心原因:python -m http.server默认会把.js文件的MIME类型识别为text/plain,但Vite默认构建的是ES模块脚本,浏览器加载ES模块时严格要求服务器返回application/javascript类型,因此触发报错。

以下是两种可行的解决方法:

方案1:自定义Python服务器脚本修正MIME类型

在dist目录下创建一个名为server.py的文件,内容如下:

from http.server import HTTPServer, SimpleHTTPRequestHandler
import mimetypes

class CustomHandler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        mimetypes.add_type('application/javascript', '.js')
        super().__init__(*args, **kwargs)

if __name__ == '__main__':
    HTTPServer(('', 8000), CustomHandler).serve_forever()

在dist目录执行启动命令:

python server.py

访问http://localhost:8000即可正常运行项目。

方案2:修改Vite配置,构建为非ES模块格式

修改Vite配置,让构建产物输出为**IIFE(立即执行函数)**格式,这种格式不需要浏览器以模块方式加载,自然不会触发MIME类型检查。

更新vite.config.js:

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  build: {
    lib: {
      entry: './src/main.js',
      formats: ['iife']
    },
    rollupOptions: {
      output: {
        entryFileNames: 'main.js' // 可选:固定输出文件名,避免hash后缀
      }
    }
  }
})

重新执行构建:

npm run build

之后在dist目录运行python -m http.server即可正常访问。

补充说明

http-server能正常运行的原因是它默认已将.js文件的MIME类型配置为application/javascript,符合ES模块的加载要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:47:28