簡體   English   中英

導入外部包 JS 文件在 Angular 上不工作 延遲加載

[英]Import an external bundle JS file is not woking on Angular Lazy loading

我正在研究 Angular 項目。 我得到了一個 HTML 模板,其中包含捆綁 css 和 js 文件。

首先,我將它們放入angular.json並進行正常路由(直接從 app.routing.ts 路由每個組件)。 這種方法效果很好。 加載了外面的js和css。

我在 angular.js 中的構建選項,

"options": {
  "outputPath": "dist/myNewApp",
  "index": "src/index.html",
  "main": "src/main.ts",
  "polyfills": "src/polyfills.ts",
  "tsConfig": "tsconfig.app.json",
  "aot": true,
  "assets": [
    "src/favicon.ico",
    "src/assets",
  ],
  "styles": [
    "src/style.185e1449062630dae048.css"
  ],
  "scripts": [
    "src/main.dd20b1e2d0fc8a3dfde3.js"
  ]
},

我的 app.routing.ts,

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'index',
    pathMatch: 'full',
  },
  {
    path: 'index',
    component: IndexComponent,
    data: {
      title: 'Page Index'
    }
  },
...

但是在我將項目結構更改為延遲加載之后。 bundle css 文件加載正常。 但是沒有加載JS文件。 似乎 bundle js 文件中的每個 function 都沒有被觸發(但瀏覽器的控制台仍然顯示它已加載到 webpack 中)。

下面是我真正使用的 app.routing.ts

export const routes: Routes = [

  {
    path: '',
    loadChildren: () => import('./layout/layout.module').then(t => t.LayoutModule)
  },

]

下面是我的 layout-routing.module.ts,

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: 'home', loadChildren: () => import('../pages/index/index.module').then(t => t.IndexModule) },
      { path: 'faq', loadChildren: () => import('../pages/faq/faq.module').then(t => t.FaqModule) },
      { path: 'contact', loadChildren: () => import('../pages/contact/contact.module').then(t => t.ContactModule) },
    ]
  },
];

webpack 顯示它已加載,

在此處輸入圖像描述

我想念什么嗎? 我已經嘗試將該 js 文件放入 assets 中並從 index.html 中調用它。 這種方法還是不行。 請幫忙。

幾天前我也遇到了這個問題,經過反復試驗,我有了解決方案。 我手動將我的 js 外部文件(從 angular.json)導入到 layout.component.ts

import { Component, OnInit } from '@angular/core';

// this files from angular.json js files external files (depend on your bootstrap js files)
import "../../assets/components/kit/core/index.js";
import "../../assets/components/airui/layout/menu-left/index.js";

@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.css'],
})

export class LayoutComponent implements OnInit {

constructor() {
}
ngOnInit(): void { 
}
}

現在工作正常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM