如何在Angular 6中导入JS文件?

4

如何在Angular 6中导入JS文件?我尝试实现一个包含JS函数的导航栏。

谢谢!

我添加了名为nav.js的JS文件。

 "scripts": [
          "src/assets/js/nav.js"
        ]

1
包含jQuery的工作示例: https://dev59.com/MVcP5IYBdhLWcg3wtcWO - slashpm
4个回答

3

Angular 6为声明js文件提供了专门的位置,即在angular.json的专用数组中。

 /projects/$(youProjectName)/architect/build/options/scripts[]

并且。
 /projects/$(youProjectName)/architect/test/options/scripts[]

作为一个例子:
npm install fast-levenshtein --save

将在 node-modules 下安装一个 js 库。

相对于项目的路径,可以这样声明 js 库文件:

"scripts": [
   "node_modules/fast-levenshtein/levenshtein.js"
]

然后在你的组件中声明要使用的变量,可以按照npm文档或@LuaXD的描述进行操作。


1
如果这是一个自定义的JS文件,我该如何声明变量? - juniortan

2
您应该在index.html中包含,例如:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
   <title>A random project</title>
   <base href="/">

   <meta name="viewport" content="width=device-width, initial- 
    scale=1">
   <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
   <link rel="stylesheet" href="https://cartodb- 
  libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" 
/>
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.core.js"></script>

<app-root></app-root>
</body>
</html>

在这个案例中,我包含了cartodb.js库,然后为了在任何组件或服务中使用cartodb.js,我使用了以下代码:
declare var cartodb: any;

在任何文件(组件、服务等)的开头。
请注意,将cartodb替换为您将使用的库的名称,例如jquery如下:
declare var jquery:any;
declare var $ :any;

你应该有类似这样的东西:
import { Injectable } from '@angular/core';
// Other imports...

declare var cartodb: any;
@Injectable()
export class ARandomService {
}

提示:如果您想使用的代码在npm中不存在,请搜索。


我们可不可以使用文件导入的方式,而不是使用声明变量的方式? - gauti
声明变量cartodb: any; 声明变量jquery: any; 声明变量jquery-ui: any;我可以在我的TypeScript中像这样导入多个库吗? - Sayed Mohd Ali

0

首先,您应该使用npm安装库。然后,该库将被添加到您的项目中的node_modules文件夹中。

现在:

如果您想将js文件导入到Angular项目中,首先应检查Angular的版本,如果您正在使用版本2和4,则应像这样编写:

      "scripts": [ "../node_modules/jquery/dist/jquery.min.js" ]

如果您使用的是高于4版本的编程语言,例如5、6或7,您应该这样编写:

      "scripts": [ "./node_modules/jquery/dist/jquery.min.js" ]

在这个例子中,我将jQuery导入到Angular项目中。希望它能正常工作。

0

如果你能掌握脚本中的函数,我建议提供一些解决方法。你可以将它们作为函数放在你的component.ts代码中,或者如果你不能或不想这样做,你只需导出/导入它们。例如:

myscript.js

  function a(){ ...}
    function b(){...}


    module.exports.a=a
    module.exports.b=b

mycomponent.component.ts

..
import a from './path/../myscript.js';
import b from './path/../myscript.js';

..
constructor(){
...
a.a()
b.b()
...
}

提示:很多时候你会发现函数是匿名的,所以你只需要给它们重新命名,例如

myscript.js

function(){..}();

将会是

myscript.js

function myCustomName(){..};
module.exports.customName=myCustomName

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接