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

为Angular 15非SSR项目集成Vite后无法正常运行求助

Angular 15 + Vite 启动异常解决方案

问题分析

直接安装Vite后启动报错,核心原因是Vite本身不内置Angular的编译支持——Angular的模板编译、装饰器处理、依赖注入等特性需要专门的Vite插件适配,仅靠Vite核心无法解析Angular项目结构。

修复步骤

1. 清理并修正package.json

你的package.json存在重复配置块,先删除重复部分,保留一份完整配置,同时安装适配Angular 15的Vite插件:

yarn add -D @vitejs/plugin-angular@0.11.0

注:0.11.0版本专门适配Angular 15,更高版本仅支持Angular 16+

修正后的package.json:

{
  "name": "app-client",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^15.0.0",
    "@angular/common": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/localize": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/router": "^15.0.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.12.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.2",
    "@angular/cli": "~15.0.2",
    "@angular/compiler-cli": "^15.0.0",
    "@types/jasmine": "~4.3.0",
    "@vitejs/plugin-angular": "^0.11.0",
    "autoprefixer": "^10.4.14",
    "jasmine-core": "~4.5.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "postcss": "^8.4.22",
    "tailwindcss": "^3.3.1",
    "typescript": "~4.8.2",
    "vite": "^4.3.1"
  }
}

2. 修正vite.config.js

添加Angular插件到配置中,让Vite能处理Angular的编译逻辑:

import { defineConfig } from 'vite';
import angular from '@vitejs/plugin-angular';
import { splitVendorChunkPlugin } from 'vite';
import { dependencies } from './package.json';

function renderChunks(deps) {
  let chunks = {};
  Object.keys(deps).forEach((key) => {
    if ([].includes(key)) return;
    chunks[key] = [key];
  });
  return chunks;
}

export default defineConfig({
  plugins: [angular(), splitVendorChunkPlugin()],
  build: {
    sourcemap: false,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: [],
          ...renderChunks(dependencies),
        },
      },
    },
  },
});

3. 调整tsconfig.json

确保TypeScript模块配置符合Vite的ES模块要求,在compilerOptions中添加:

"module": "ESNext",
"moduleResolution": "NodeNext"

4. 检查index.html入口

确保入口脚本使用ES模块格式,路径正确:

<script type="module" src="/src/main.ts"></script>

5. 重新启动项目

yarn dev

关键说明

  • Angular的Vite插件负责处理模板编译、装饰器转换、Angular特定的模块解析等核心逻辑,这是直接用Vite无法替代的
  • 若后续需要更完善的Angular+Vite支持,可升级到Angular 16+使用官方@angular/build(默认集成Vite),Angular 15仅能通过第三方插件适配

内容的提问来源于stack exchange,提问作者Aldemar Cuartas Carvajal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:57:54