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

Angular 4项目指定路径执行ng serve报错:node_modules为空

Why This Happens & How to Fix It

Hey there! The issue here is that ng serve doesn't treat the path you pass as the project directory to switch into. Instead, it always looks for your project's dependencies (like node_modules) and config files (angular.json, package.json) in your current working directory. When you run ng serve /hardware/angular-src from root, the CLI is still checking /root for node_modules—which is empty, hence the error.

Quick Fixes

1. Switch to the Project Directory First (Most Straightforward)

You can combine the directory switch and serve command into one line so you don't have to do two separate steps:

cd /hardware/angular-src && ng serve

This works exactly like when you manually navigate to the folder first—it tells your terminal to move into the project directory before running ng serve.

2. Use the --cwd Flag (Angular CLI 8+)

If you prefer not to switch directories manually, Angular CLI added the --cwd flag in version 8 to let you specify the working directory directly. Run this from root:

ng serve --cwd /hardware/angular-src

This tells the CLI to execute the command as if you were already inside /hardware/angular-src, so it'll find your node_modules and config files correctly.

3. Use npm Scripts for Repeated Use (Optional)

If you start this project often, you can set up a quick npm script to make it even easier. Open your project's package.json (located at /hardware/angular-src/package.json) and add a start script if it doesn't already exist:

"scripts": {
  "start": "ng serve",
  // keep any other existing scripts here
}

Then, from root, you can run:

npm start --prefix /hardware/angular-src

The --prefix flag tells npm to run the script from the specified directory.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:39:04