在Angular项目中安装Bootstrap

4

你好,我在我的机器上安装了最新版本的Angular CLI。我试图在Angular项目中安装Bootstrap。

以下是我遵循的步骤:

  1. ng new Demo
  2. npm install bootstrap jquery --save
  3. 然后在vs code中打开项目的angular.json文件,复制以下代码:

    "styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.css" ], "scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../node_modules/bootstrap/dist/js/bootstrap.js" ]

之后我运行了该项目的ng serve命令,但出现了以下错误信息:

Angular Live Development Server is listening on localhost: 4200, open your browser on http://localhost:4200/ ** 91% additional asset processing scripts-webpack-plugin× 「wdm」: Error: ENOENT: no such file or directory, open 'D:\Angular\node_modules\jquery\dist\jquery.min.js'

请注意,在angular.json文件中添加引用的CSS和JS文件时,确保路径正确。此外,您还需要检查本地是否存在所需的CSS和JS文件。

你尝试过重新构建应用程序并再次运行serve命令吗? - Prachi
1
我认为您提供的路径是错误的,因为angular.json文件位于项目工作区的根目录中... 因此,您提供的路径应该是 "./node_modules/jquery/dist/jquery.min.js" 而不是 **"../node_modules/jquery/dist/jquery.min.js"**,并且对于angular.json文件中的所有其他脚本也适用。 - Abinesh Devadas
非常感谢Abinesh,它已经能够工作了。但是glyphicon图标没有显示。 - Lewis
2个回答

3
从 Angular 6 开始,CLI 项目将使用 angular.json 而不是 .angular-cli.json 进行构建和项目配置。
每个 CLI 工作区都有项目,每个项目都有目标,每个目标可以有配置。 文档
. {
  "projects": {
    "my-project-name": {
      "projectType": "application",
      "architect": {
        "build": {
          "configurations": {
            "production": {},
            "demo": {},
            "staging": {},
          }
        },
        "serve": {},
        "extract-i18n": {},
        "test": {},
      }
    },
    "my-project-name-e2e": {}
  },
}

在你的 angular.json 中,在 build 目标下的样式和脚本数组中添加文件路径,使用 ./ 代替 ../

Bootstrap 4 不再支持 Glyphicons,你可以使用 Font Awesome 替代:
执行 npm install --save font-awesome 并将文件路径添加到样式数组中

 "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ng6",
            "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","./node_modules/bootstrap/dist/css/bootstrap.min.css"
               "./node_modules/font-awesome/css/font-awesome.css"
            ],
            "scripts": ["./node_modules/jquery/dist/jquery.min.js",
                       "./node_modules/bootstrap/dist/js/bootstrap.min.js"]
          },

非常感谢,Vikas。错误已经消失了。但是glyphicon图标没有显示。 - Lewis
@Lewis 我已经相应地更新了我的答案,如果有帮助,请标记并点赞。 - Vikas
完成了,但无法点赞。因为我的声望不到15。 - Lewis

0
将您的命令行放在项目上,然后运行:
npm install bootstrap@next

然后,进入你的IDE,打开Angular.json文件,在styles中添加以下内容:

"styles": [ "node_modules/bootstrap/dist/css/bootstrap.css", "src/styles.css" ]

对于脚本也做同样的操作:

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

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