【问题标题】:Failed to load resource from bower_components even with correct file path即使文件路径正确,也无法从 bower_components 加载资源
【发布时间】:2023-04-09 14:31:01
【问题描述】:

我在处理 Web 项目时遇到了一些令人沮丧的 404 错误。我正在为我的 CSS 和 JS 文件使用这个文件结构:

bower_components
    bootstrap
        |dist
            |css
               | bootstrap.min.css
    angular
        |angular.min.js
    jquery
        |dist
            |jquery.min.js
dist
lib
    |farbtastic.js
node_modules
src
    |img
    |styles
    |scripts
    |view1
    |view2
    |index.html //running browserSync from this folder using this file as index

当我尝试使用适当的语法引用 index.html 中的文件时:

<link rel="stylesheet" type="text/css" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">

我收到 404“加载资源失败”错误。

../ 语法似乎是正确的,我的控制台显示它正在查看http://localhost:3000/bower_components/bootstrap/dist/css/bootstrap.min.css 中的正确位置。

是不是我做的不对?

【问题讨论】:

    标签: javascript html css browser-sync


    【解决方案1】:

    应用程序的根目录是“src”文件夹。当您从“../bower_components/”请求 bootstrap.min.css 时,您是在告诉浏览器升级 1 级。因为您已经在应用程序的根目录,所以“../bower_component”本质上与“bower_component”的作用相同。

    你可以:

    1. move your index.html 1 level up
    2. move your bower_components inside src
    3. have some kind of build(gulp/grunt) to reorganize them in a way where the bower_components is within the root folder.
    

    【讨论】:

    • 好的,有道理。 #2为我工作,所以解决了我的问题。谢谢!
    • 请问如何使用 gulp 进行第三步?我试过但找不到相同的解决方案。我正在为多个项目使用单个引导安装。只是练习。
    • gulp.src("bower_components/bootstrap/dist/css/bootstrap.min.css").dest("dist/bower_components/bootstrap/dist/css/");
    【解决方案2】:

    由于您的应用程序的根目录是src 文件夹,您仍然可以使用链接从 bower_components 加载

    <link rel="stylesheet" type="text/css" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
    

    这样配置你browserSync.init

    browserSync.init({
            server: {
                    baseDir :"src",
                    routes:{
                        "/bower_components" : "bower_components"
                    }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 2017-05-26
      • 2013-07-16
      • 1970-01-01
      相关资源
      最近更新 更多