简体   繁体   English

使用 angular-cli 为 Angular 中的静态文件添加前缀路径

[英]Adding prefix path to static files in Angular using angular-cli

I have an existing django project where I am serving static files over /static/ path.我有一个现有的 django 项目,我通过 /static/ 路径提供静态文件。 I am migrating a part of the application to angular2, to be specific mobile version of the site.我正在将应用程序的一部分迁移到 angular2,以成为网站的特定移动版本。

Adding <base href="/"> to index.html loads static files www.example.com/main.js gets 404 here.添加<base href="/">到 index.html 加载静态文件 www.example.com/main.js 在这里得到 404。 Adding <base href="/static/"> to index.html loads static files correctly, but when the application bootstraps, it changes the url to /static/ (i am using routers), although my url should be /order/.<base href="/static/">到 index.html 正确加载静态文件,但是当应用程序引导时,它将 url 更改为 /static/(我正在使用路由器),尽管我的 url 应该是 /order/。

is there a way of using base href as / but adding prefix to script and style files using angular-cli有没有办法使用 base href 作为 / 但使用 angular-cli 为脚本和样式文件添加前缀

using version ng --version使用版本ng --version

@angular/cli: 1.0.0-rc.0
node: 6.9.1
os: win32 x64
@angular/common: 2.4.9
@angular/compiler: 2.4.9
@angular/core: 2.4.9
@angular/forms: 2.4.9
@angular/http: 2.4.9
@angular/platform-browser: 2.4.9
@angular/platform-browser-dynamic: 2.4.9
@angular/router: 3.4.9
@angular/cli: 1.0.0-rc.0
@angular/compiler-cli: 2.4.9

You can use --deploy-url to prefix path of your generated static files.您可以使用 --deploy-url 为生成的静态文件的路径添加前缀。 ng build --deploy-url /static/ . ng build --deploy-url /static/ It will prefix path of js files with /static/ in generated index.html like this:它将在生成的 index.html 中使用/static/前缀 js 文件的路径,如下所示:

<script type="text/javascript" src="/static/inline.bundle.js"></script>

From help doc:从帮助文档:

--deploy-url (String) URL where files will be deployed.

Updated answer based on comments.根据评论更新答案。

Using angular CLI 6.1.1使用 Angular CLI 6.1.1

This how I do it, you need to use the build flag --base-href这就是我的做法,您需要使用构建标志--base-href

Example例子

ng build --prod --base-href=/dist/my-app/

and I access the site like this http://127.0.0.1:5500/dist/my-app/index.html我像这样访问网站http://127.0.0.1:5500/dist/my-app/index.html

Official document reference here官方文档参考这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM