Grunt usemin和绝对(不存在)文件路径

时间:2015-04-30 15:29:09

标签: angularjs gruntjs grunt-usemin

我的目录结构如下所示,我有一个绝对路径/static映射到我的public dir

+public/
  +--app/
  +--dist/
  |--Gruntfile.js
  |..
  |..

目前,一切都很顺利,我最终使用dist中的缩小/ rev'd文件,但index.html文件包含相对路径,如:

<script src="some-file.56a75bad.js"></script>

当我需要它们时:

<script src="/static/dist/some-file.56a75bad.js"></script>

似乎无法弄清楚如何实现这一点,我尝试过的所有内容都给出了正确的文件路径但不是rev​​'d文件,即:

<script src="/static/dist/some-file.js"></script>

1 个答案:

答案 0 :(得分:0)

我的解决方案: copy任务将所有脚本移动到.tmp文件夹。然后uglify任务运行并输出到.tmp中要解析的绝对路径的文件夹层次结构。运行这两个任务后,我有一个看起来像这样的文件夹结构(mid build):

public/
  +--.tmp/
    +--static/
      +--dist/
        |--application.min.js
        |--dependencies.min.js
  +--app/
  +--bower_components/
  +--dist/
  |--Gruntfile.js
  |--index.html

我的index.html

的一小部分
<!-- build:js /static/dist/dependencies.min.js -->
<script src="/static/dist/dependencies.min.js"></script>
<!-- endbuild -->

<!-- build:js /static/dist/application.min.js -->
<script src="/static/dist/application.min.js"></script>
<!-- endbuild -->

现在正常运行useminPrepare filerevusemin任务。

我的GruntFile:

module.exports = function(grunt) {

    require('load-grunt-tasks')(grunt);

    grunt.config.init({

        useminPrepare: {
            html: 'dist/index.html',
            options: {
                dest: './dist'
            }
        },

        usemin:{
            html:['dist/index.html'],
            options: {
                assetsDirs: ['.tmp']
            }
        },

        copy:{
            html: {
                src: './index.html',
                dest: 'dist/index.html'
            },
            javascripts: {
                cwd: '',
                src: 'app/scripts/**',
                dest: '.tmp',
                expand: true
            }
        },

        uglify: {
            build: {
                options: {
                    mangle: true
                },
                files: {
                    '.tmp/static/dist/application.min.js': ['.tmp/app/**/*.js'],
                    '.tmp/static/dist/dependencies.min.js': [
                        'bower_components/jquery/dist/jquery.js',
                        'bower_components/angular/angular.js'
                        // All my other 3rd party libs, I realized this can be done in index.html but there's environmental constraints making that not possible
                    ]
                }
            }
        },

        filerev: {
            dist: {
                src: ['.tmp/static/dist/application.min.js', '.tmp/static/dist/dependencies.min.js'],
                dest: 'dist'
            }
        }

    });

    grunt.registerTask('build',[
        'copy:javascripts',
        'copy:html',
        'uglify',
        'useminPrepare',
        'filerev',
        'usemin'
    ]);
};