如何将现有Angular-CLI项目转换为无CLI的Angular项目?
Hey there! Let's tackle your two main goals: converting your Angular CLI project to a CLI-free setup, and resolving that stubborn CORS issue without relying on localhost:4200. Here's a step-by-step breakdown for both:
Moving away from Angular CLI means taking control of the build process yourself—usually with Webpack, though you could also use Rollup or Vite. Let's go with Webpack since it's the most common alternative:
Step 1: Set Up Your Basic Project Structure
First, create a new folder for your CLI-free project, then copy over core files from your existing CLI project:
- Copy everything inside
src/app/(components, modules, services, etc.) - Copy
src/assets/and any global styles (likestyles.css) - Create a
dist/folder for your production builds
Step 2: Install Dependencies
Initialize npm if you haven't already:
npm init -y
Install Angular core dependencies:
npm install @angular/core @angular/common @angular/compiler @angular/platform-browser @angular/platform-browser-dynamic rxjs zone.js
Install build tools (Webpack and related plugins):
npm install webpack webpack-cli webpack-dev-server @babel/core babel-loader @babel/preset-env @babel/preset-typescript typescript ts-loader angular-template-loader html-webpack-plugin --save-dev
Step 3: Configure Webpack & TypeScript
Create a webpack.config.js file in your project root with this basic setup:
const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); module.exports = { entry: './src/main.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.[contenthash].js' }, module: { rules: [ { test: /\.ts$/, use: ['ts-loader', 'angular-template-loader'], exclude: /node_modules/ }, { test: /\.html$/, use: 'html-loader' }, { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, resolve: { extensions: ['.ts', '.js'] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], devServer: { open: true, historyApiFallback: true // For Angular's routing } };
Create a tsconfig.json with Angular-compatible settings:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "strict": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "moduleResolution": "node", "skipLibCheck": true, "esModuleInterop": true, "resolveJsonModule": true, "baseUrl": "./", "paths": { "@/*": ["src/*"] } }, "include": ["src/**/*"] }
Step 4: Update Package Scripts
Add these scripts to your package.json to build and run your app:
"scripts": { "build": "webpack --mode production", "start": "webpack-dev-server --mode development" }
Step 5: Verify Bootstrap Code
Make sure your src/main.ts has the correct Angular bootstrap code (it should already if you copied from the CLI project):
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err));
localhost:4200 Since you want to ditch localhost:4200, here are the most reliable solutions:
Option 1: Serve Your App From the Same Domain as Your API
This is the most permanent fix. After running npm run build, deploy the dist/ folder to the same domain (or subdomain) as your backend API. For example:
- API lives at
https://yourdomain.com/api - Angular app lives at
https://yourdomain.com
Since both are on the same origin, browsers won't throw CORS errors.
Option 2: Use a Reverse Proxy with Webpack Dev Server
If you still need a dev server (not production), configure Webpack to proxy API requests to your backend. Update the devServer section in webpack.config.js to use a different port (e.g., 3000) and add proxy rules:
devServer: { open: true, historyApiFallback: true, port: 3000, // Use any port except 4200 proxy: { '/api': { target: 'https://your-backend-api.com', // Replace with your API URL changeOrigin: true, secure: false // Disable if your API uses a self-signed cert } } }
Now, in your Angular services, make requests to /api/your-endpoint instead of the full API URL. Webpack will forward these requests to your backend, and since the browser sees the request coming from localhost:3000 (same origin as your dev app), no CORS errors.
Option 3: Serve Built Files via a Simple HTTP Server
Compile your app with npm run build, then use a tool like serve to host it on a custom port:
npm install -g serve serve -s dist -l 3000
Then ask your backend team to add http://localhost:3000 to their CORS allowed origins. This works but requires backend configuration, so it's less ideal than the reverse proxy method.
内容的提问来源于stack exchange,提问作者Tzof

