GruntJS - grunt 构建后错误的图像路径

2024-01-22

Grunt 弄乱了我的缩小 CSS,我不知道为什么以及如何避免它。

简而言之,在缩小之前我有一些像这样的背景图像:

.head-image {
  height: 380px;
  background: url("../images/head1_bg.png") repeat-x;
  -webkit-background-size: cover;
  background-size: cover;
}

然后,在整个过程之后,我得到了一个缩小的 CSS,如下所示(片段):

[...]background:url(/home/domo/projects/lp/.tmp/images/head1_bg.png) repeat-x;background-size:cover}[...]

上述路径不仅是绝对路径,而且是错误的,因为图像可以在dist/images,不在.tmp/images(甚至不存在......)。

这里提到了一个非常相似的问题:自耕农#824 https://github.com/yeoman/yeoman/issues/824
我从该线程中尝试了 2 个解决方案(#17759188 https://github.com/yeoman/yeoman/issues/824#issuecomment-17759188 and #29137057 https://github.com/yeoman/yeoman/issues/824#issuecomment-29137057)但无济于事。

我什至尝试使用据称已修补的 yeoman 版本,如另一个 Stack Overflow 问题中所述(Yeoman CSS 图像路径 https://stackoverflow.com/questions/14316643/yeoman-css-image-paths/14341950#14341950)发帖,仍然没有成功......

也许有人已经走过这条路并找到了我在互联网上找不到的解决方案。

Edit:我可以再添加一个细节

HTML 部分中的图像路径不受影响,如下所示:
ng-src="./images/box_{{$index+1}}.png"

Gruntfile.js

// Generated on 2014-07-14 using generator-angular 0.8.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['bowerInstall']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: true
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ]
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ],
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    bowerInstall: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath: '<%= yeoman.app %>/'
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: '<%= yeoman.app %>/bower_components/'
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: '<%= yeoman.app %>/bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>']
      }
    },

    // The following *-min tasks produce minified files in the dist folder
    cssmin: {
      options: {
        root: '<%= yeoman.app %>'
      }
    },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ngmin tries to make the code safe for minification automatically by
    // using the Angular long form for dependency injection. It doesn't work on
    // things like resolve or inject so those have to be done manually.
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%= yeoman.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    }
  });


  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'bowerInstall',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'bowerInstall',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngmin',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'rev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};

前段时间,我在 cssmin 上遇到了类似的问题......

我的配置是:

cssmin: {
   options: {
     root:  '<%= yeoman.app %>'
   }
},

然后我已经删除了root财产并解决了问题。

UPD1:此外,您还需要将图像添加到configutarion中的assetsDirs中以供使用:

usemin: {
  html: ['<%= yeoman.dist %>/{,*/}*.html'],
  css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
  options: {
    assetsDirs: ['<%= yeoman.dist %>', '<%= yeoman.dist %>/images']
  }
},

UPD2:关于图像ng-src="./images/box_{{$index+1}}.png",不可能直接用 usemin 处理它们,因为没有办法处理这个表达式中的文件修订...

但您可以添加带有图像网址的单独地图,例如:

<div ng-init="boxes=[
    {src:'images/box1.png'},
    {src:'images/box2.png'}, 
    {src:'images/box3.png'}]>
    ....
    <img ng-src={{boxes[$index].src}}/>
    ....
</div>

并使用附加模式处理这些地图以供使用:

usemin: {
  html: ['<%= yeoman.dist %>/{,*/}*.html'],
  htmlExtra: ['<%= yeoman.dist %>/{,*/}*.html'],
  css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
  options: {
    assetsDirs: ['<%= yeoman.dist %>', '<%= yeoman.dist %>/images'],
    patterns:{
        htmlExtra:[
            [/['"]?src['"]?\s*:\s*['"]([^"']+)['"]/gm, 'Replacing urls in image maps']
        ]
    }
  }
},

然后构建后你会得到类似的东西:

<div ng-init="boxes=[
        {src:'images/box1.xxxx.png'},
        {src:'images/box2.xxxx.png'}, 
        {src:'images/box3.xxxx.png'}]">
    ....
    <img ng-src={{boxes[$index].src}}/>
    ....
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GruntJS - grunt 构建后错误的图像路径 的相关文章

随机推荐

  • 如何使用 cxf 组件使用 Apache Camel 调用第三方 Web 服务

    我浏览了 Apache Camel 网站和 Camel in Action 上的示例 两者都重点关注公开 Web 服务 我在网上找到的唯一示例不起作用 我正在尝试访问第三方网络服务 wsdl http www webservicex net
  • 从表格中删除内容并重新格式化表格

    我想要做 我的页面以以下格式显示表格的数据 有什么方法可以删除具有空白值的内容并重新格式化表格 如下所示 额外细节 实际表格中的任何值都可能为空白 请参阅第一张图片 我想删除那个特定的Test行 具有空白值 并通过均匀分布剩余内容来重新格式
  • SBT 挂起等待孤立子进程完成

    在我的 SBT 0 13 16 版本中 我有以下任务 startThing var bin path s file getAbsolutePath bin val result s bin path start thing if resul
  • iOS 5:您可以覆盖特定类中的 UIAppearance 自定义吗?

    我正在构建一个带有许多视图控制器的应用程序 我有一个UITabBarController其中容纳 4UINavigationController 我希望所有导航栏都是我的自定义颜色 比如蓝色 我通过在应用程序委托中执行此操作来实现 UINa
  • 设置鼠标位置

    我需要能够将鼠标位置设置到屏幕 窗口的中间 我怎样才能做到这一点 该文档似乎表明CGDisplay移动光标到点 http developer apple com library mac documentation GraphicsImagi
  • Git 远程恢复

    我是 Git 新手 正在使用 WebStorm 来推送和拉取我的代码 我们正在开展一个共同的项目 昨晚我的朋友更新了一些代码并推送了更改 今天 我拉取了代码并合并了更改 但我错误地保留了更改并放弃了拉取请求提供的更改 然后将这些更改推送到
  • 如何获取 Laravel CSRF-token 以通过 React 中的 fetch post 请求发送它?

    我正在使用开发网络应用程序创建反应应用程序和拉维尔 创建反应应用程序在 localhost 3000 上运行开发项目 而 laravel 后端在 localhost 8080 上运行 这是我的代码的一部分 const onSubmit e
  • 修复了 Highcharts 中的 y 轴标签宽度

    我正在构建一个数据演示 其中两个 Highcharts 图表垂直堆叠 旨在共享相同的 x 轴单位和对齐方式 就像这样 请注意 由于两个图表的 y 轴范围不同 因此 y 轴标签的宽度不同 因此图表本身的宽度略有不同 破坏了良好的 x 轴对齐
  • 如何让 System.Net.Http.HttpClient 不遵循 302 重定向?

    Using 来自 NuGet 的 HttpClient http nuget org packages HttpClient 应用程序使用 client PostAsync 发送帖子 我希望它不遵循 302 重定向 how 我想我可以设置A
  • 将元描述和开放图谱协议描述合并到一个标签中

    是否可以将元描述和开放图协议描述结合起来 当它们包含相同的内容时合而为一 是的 您可以将它们结合起来 为了测试它 我制作了下面的简单 HTML 页面 将其上传到服务器 然后通过 Facebook 运行该页面网址检查器 https
  • 更新 LayoutView 的模型

    JSBin 链接 http jsbin com rosadomisa edit html js console output 单击 Clicks 链接可查看显示更新后的模型数据的控制台 但原始显示的 HTML 不会更改 更新 LayoutV
  • 将 Windows 对话框错误消息重定向到控制台

    有谁知道如何重定向 捕获模式 Windows 错误对话框 对于仅尝试运行程序并捕获退出代码和 stdout stderr 输出的非交互式命令行程序来说 这确实是个问题 此问题的最新实例是一个模态 Windows 对话框 其形式如下 The
  • AWS S3 最大文件和上传大小

    AWS S3 文档说 单个 Amazon S3 对象的大小范围最小为 0 字节到最大 5 TB 最大的物体可以 一次 PUT 上传的大小为 5 GB 如果我只能上传 5GB 的文件 如何存储 5TB 的文件 根据文档here http do
  • Python 3.5 async for 阻止 ioloop

    我有一个带有两个处理程序的简单 aiohttp 服务器 第一个在中进行一些计算async for环形 第二个仅返回文本响应 not so long operation以最慢的递归实现返回第 30 个斐波那契数 大约需要一秒钟 def not
  • Akka.Net 发送巨大消息(最大帧大小)

    我有一个关于增加最大帧大小和发送 接收缓冲区大小值的问题 他们的高度有限制吗 我将大量数据传递到系统中 比如 20mb 然后用于计算一些结果并返回 将上述参数设置为 100mb 会导致消息被丢弃 在这种情况发生之前我可以通过的最大块大约是
  • 如何在 LDAP 中按 DN 进行搜索?

    我正在从 LDAP 中提取有关用户的信息 这包括 directReports 它是完整的CN cnBlah OU ouBlah DC dcBlah形式 我正在尝试再次查找有关该记者的信息 到目前为止 我能够真正找到所述用户的唯一方法是打破C
  • 关于“==”运算符行为的解释

    在下面的非常简单的示例中 我无法理解 运算符的行为 A lt c 10 20 10 10 20 30 B lt c 40 50 60 70 80 90 df lt data frame A B df df A c 10 20 it retu
  • mongodb ISODate 问题

    我正在使用java IDE是eclipse 在mongodb上查询 下面是我的java代码 DBObject query new BasicDBObject ObjectId id new ObjectId 529f280b90ee58cb
  • SpringBoot:配置生产环境与开发环境

    我在使用 SpringBoot 1 5 1 时遇到问题 我已经创建了application properties and application dev properties对于我的开发环境 主要区别在于持久性 在生产中 applicati
  • GruntJS - grunt 构建后错误的图像路径

    Grunt 弄乱了我的缩小 CSS 我不知道为什么以及如何避免它 简而言之 在缩小之前我有一些像这样的背景图像 head image height 380px background url images head1 bg png repea