Angular 8 运行 npm 上的 dist 文件夹 运行 start-dev

Angular 8 run dist folder on npm run start-dev

我正在尝试 运行 我的 dist 文件夹,而不是 ng serve。为此,我在 package.json.

中写了一个脚本

start-dev: ng build && http-server dist

问题是我希望它在我保存任何文件时自动 运行。它还会再次构建整个 npm,这是一个非常缓慢的过程。关于我该怎么做的任何其他方法?并且做得更快?

您可以在 运行 ng build 时使用 --watch 标志。因此命令将是 ng build --watch 以在您更改文件时自动重建。

要自动重启 http-server dist/<app_name> 命令,您可以使用 nodemon

对于 nodemon,命令将是 nodemon --watch dist --exec 'http-server dist/<app_name>'

你可以运行像这样把两个命令放在一起 ng build --watch & nodemon --watch dist --exec 'http-server dist/<app_name>'

以上命令将协同工作。 Angular 将重建 dist 文件夹,nodemon 将在 dist 文件夹更改时重新启动您的服务器。

如 Chris 的回答所示,您可以在使用 ng build --watch 时自动重建您的应用。

如果您只想提供最新版本的应用程序,您可以使用 -c-1 选项 (doc) 从 http-server 禁用缓存(默认情况下启用)

在 linux 上(并行使用单个 & 到 运行 脚本)

"start-dev": "ng build --watch & http-server -c-1 dist", 

在 windows 上(注意 start 命令):

"start-dev": "start ng build --watch && start http-server -c-1 dist", 

备注

  • 您的浏览器可能在您像上面那样停用缓存之前已经缓存了文件dist,因此请手动清除缓存一次。

    之后你就不需要这样做了
  • 这个解决方案不会重新加载页面,你必须自己做

  • http-server 不支持回退,如果您使用 angular 的默认策略,这可能是个问题。因此,如果您在 http://localhost:8080/module1/path1 并重新加载页面,您将收到 404。 您需要重新加载 http://localhost:8080 并从应用路由器

    导航到正确的 url
  • 根据您的 angular.json,输出文件夹可能是 distdist/projectNamedist/projectName/browser,或者您指定的任何内容

最好安装精简版服务器。 安装精简版服务器:-

npm install --global lite-server

然后在cmd或者终端打开dist文件夹

lite-server

资源:- https://www.npmjs.com/package/lite-server