Angular 6, ng build index.html 控制台报错

Angular 6, after ng build index.html gets errors in console

我遇到了问题,请帮助我解决这个问题。 问题是,当我在 CLI 中执行 ng build 并转到 dist 文件夹和 运行 index.html 文件时,控制台会收到文件路径错误。

Failed to load resource: net::ERR_FILE_NOT_FOUND
polyfills.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND
styles.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND
scripts.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND
vendor.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND
main.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND
/D:/favicon.ico:1 Failed to load resource: net::ERR_FILE_NOT_FOUND

href 属性 的默认 base 被定义为 angular cli 项目的 /。如果你正在构建项目并通过直接打开index.html文件访问它,那么HTML要加载的所有.js将从'/' directory加载。

例如,如果您正在使用 windows 并且您的构建存在于 C:\users\xys\ng\dist\index.html 中,并且您有 <script type="text/javascript" src="runtime.js"></script> 在您的 HTML 中,浏览器将在 C:\runtime.js.

中查找 .js 文件

要解决这个问题,您可以将所有文件复制到驱动器的根目录(不建议),或者您可以创建一个本地服务器,然后将静态文件提供给该服务器(首选方法)。

只与路径有关,只需在构建时使用--base-href标志即可-

ng build --prod --base-href ./

现在它会在您的 index.html -

中生成类似于以下内容的行
<base href="./">
<!-- Note the file names here -->
<script type="text/javascript" src="runtime.30458714a8af1a2e7153.js"></script>
<script type="text/javascript" src="polyfills.db85ebdc34f3cf0f4d3f.js"></script>
<script type="text/javascript" src="scripts.e8fe6486441dc07e00c6.js"></script>
<script type="text/javascript" src="main.f9ea86a83ded92312d0f.js"></script>

就是这样!它无处不在,您只需要部署生产版本,就可以开始了!

Also, please note that if you are trying to run index.html right from your files, it won't work. You'll need to place it on a http server (for example, XAMPP for local)