繁体   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