【问题标题】:Adding prefix path to static files in Angular using angular-cli使用 angular-cli 在 Angular 中为静态文件添加前缀路径
【发布时间】:2017-07-22 13:54:08
【问题描述】:

我有一个现有的 django 项目,我通过 /static/ 路径提供静态文件。我正在将应用程序的一部分迁移到 angular2,成为该网站的特定移动版本。

<base href="/"> 添加到 index.html 会加载静态文件 www.example.com/main.js 在此处获取 404。 将<base href="/static/"> 添加到 index.html 会正确加载静态文件,但是当应用程序启动时,它会将 url 更改为 /static/(我正在使用路由器),尽管我的 url 应该是 /order/。

有没有办法使用基本 href 作为 / 但使用 angular-cli 为脚本和样式文件添加前缀

使用版本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

【问题讨论】:

    标签: javascript django angular typescript angular-cli


    【解决方案1】:

    您可以使用 --deploy-url 为生成的静态文件的路径添加前缀。 ng build --deploy-url /static/。它将在生成的 index.html 中为 js 文件的路径添加 /static/ 前缀,如下所示:

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

    来自帮助文档:

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

    示例:

    ng build --prod --deploy-url=example.com/scripts/
    

    根据 cmets 更新答案。

    【讨论】:

    • 资产中的静态文件呢?
    • 是的,-d 不是有效的命令,所以 --deploy-url 是唯一的。
    • 图片怎么样?如果我使用 base href 这样做,它将为所有路由添加前缀
    【解决方案2】:

    使用 Angular CLI 6.1.1

    我是这样做的,你需要使用构建标志--base-href

    示例

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

    我像这样访问该网站http://127.0.0.1:5500/dist/my-app/index.html

    官方文档参考here

    【讨论】:

    • 这不是 OP 想要的,这只是在 href 中更改 &lt;base href="/"&gt;
    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 2017-09-05
    • 2018-03-18
    • 1970-01-01
    • 2017-12-31
    • 2015-01-30
    • 2018-02-21
    • 2017-06-09
    相关资源
    最近更新 更多