如何在Angular 6项目中导入JS文件?
Hey there! You’ve already taken the first step by adding your nav.js to the scripts array in your config—great start! Let’s break down the rest of the process to get that navigation bar working properly:
1. 确认配置生效并重启开发服务器
First, double-check that your angular.json (Angular 6 uses this instead of the old .angular-cli.json) has the correct path to nav.js:
"architect": { "build": { "options": { "scripts": [ "src/assets/js/nav.js" ] // 其他配置项... } } }
重要提示:修改完
angular.json后,一定要重启你的Angular开发服务器(停止ng serve再重新启动),否则新的脚本配置不会生效。
2. 解决TypeScript类型报错
Since TypeScript doesn’t know about the global functions in your nav.js file, you’ll need to declare them in the component where you want to use the navigation logic. For example, if your nav.js has a function called initNav(), add this declaration at the top of your component file:
declare function initNav(): void;
Replace initNav() with the actual name of the function(s) in your nav.js file.
3. 在组件中调用JS函数
Now you can call the function from your component’s lifecycle hook—ngOnInit() is perfect here because it runs after the component’s DOM has been initialized:
import { Component, OnInit } from '@angular/core'; // 声明全局JS函数 declare function initNav(): void; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit { constructor() { } ngOnInit(): void { // 调用导航栏初始化函数 initNav(); } }
额外情况:如果你的nav.js是ES6模块化的
If you wrote nav.js as an ES6 module (using export), you don’t need to add it to the scripts array at all. Just import the function directly in your component:
// 注意路径要根据你的组件位置调整 import { initNav } from '../../assets/js/nav.js';
Then call it in ngOnInit() like before.
小提醒
- Make sure the DOM elements your
nav.jsfunction interacts with exist in your component’s template—otherwise you’ll get "element not found" errors. - If
nav.jsdepends on other libraries (like jQuery), add those libraries to thescriptsarray beforenav.jsso they load first.
内容的提问来源于stack exchange,提问作者George

