[英]How to use external JS files in Angular 6
我用 Angular 开始了一个项目,但我从没想过安装它的最新版本会给我带来一些问题。 我也在使用 Materialize,所以当我尝试“导入”它的 Javascript 文件时它不起作用。 我不知道为什么,我从上周五开始就一直在寻找答案,但一无所获。
我已经更改了 angular.json 文件并在其中引用了我的 JS 位置,但这还不够。
PD 我不能使用 CDN 来实现 JS。
angular 6 及更高版本的 CLI 项目使用angular.json
而不是.angular-cli.json
进行构建和项目配置。 这意味着您正在使用 Angular 6。
从 v6 开始,文件的位置已更改为angular.json
。 由于不再有前导点,默认情况下文件不再隐藏并且处于同一级别。 这也意味着 angular.json 中的文件路径不应包含前导点和斜线,即您应该提供绝对路径
从 npm 安装 MaterializeCSS 和 angular2-materialize
npm install materialize-css --save
npm install angular2-materialize --save
npm install jquery@^2.2.4 --save
npm install hammerjs --save
安装所有必需的依赖项后,将它们添加到angular.json
样式和脚本数组
"styles": [
"src/styles.css",
"node_modules/materialize-css/dist/css/materialize.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/hammerjs/hammer.js",
"node_modules/materialize-css/dist/js/materialize.js"
]
配置
angular.json 配置中的样式和脚本选项现在允许直接引用包:
之前: "styles": ["../node_modules/bootstrap/dist/css/bootstrap.css"]
之后: "styles": ["bootstrap/dist/css/bootstrap.css"]
聚苯乙烯
Additonal Info
: Error import javascript library in typescript
我认为关键是:配置的正确位置。 我们有两个地方可以粘贴脚本的路径。 (角 CLI:6.1.5)
第一个是:(项目 => 你的应用程序名称 => 架构师 => 构建)
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/<your app name>",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
},
"configurations": { ... }
}
第二个是:(项目 => 你的应用程序名称 => 架构师 => 测试) - 错误的地方
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css"
],
"scripts": [
],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
}
之后,您的浏览器上应该有类似的内容:
我希望它有所帮助;)
js 总是用“”写在脚本标签中。
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"Vhls": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/Vhls",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"node_modules/videogular2/fonts/videogular.css",
"src/styles.scss"
],
"scripts": [
"src/assets/js/hls.min.js"
]
},
"configurations": {...............
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.