javascript - 使用 grunt 按顺序连接文件

标签 javascript jquery gruntjs grunt-contrib-concat

我是咕噜新手 我想使用 grunt 将 java 脚本文件连接到一个文件 我有 6 个 js 文件,但它们需要按某种顺序运行代码,而不出现像 jquery 应首先加载的错误 但来自 grunt 的结果文件不保留这个序列 我尝试了很多方法,例如将它们排列在 src 中或创建多个文件夹,但它不起作用

注意 - 当我通过复制和粘贴在一个文件中手动连接时,它工作正常 那么有没有任何命令可以让 grunt 按照我在 src 中编写的顺序连接这些文件作为示例 这也是我的 gruntfile.js

module.exports = function(grunt) {

  // 1. All configuration goes here
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),




    // 1 - this is contecnate js files call them in one file only
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['src/public/js/jquery.min.js','src/public/js/bootstrap.js','public/js/modernizr.custom.77555.js',
          'public/js/jquery.magnific-popup.js',
     'public/js/jquery.mixitup.min.js','public/js/popup-box.js' ],
        dest: 'dist/1newbuilt.js',
      },
    },



    uglify: {
      build: {
        src: 'dist/1newbuilt.js',
        dest: 'dist/1newbuilt.min.js'
      }
    }


  });

  // end 1 - this is contecnate js files call them in one file only







  // 3. Where we tell Grunt we plan to use this plug-in.
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
  grunt.registerTask('default', ['concat', 'uglify']);

};

我需要按某些顺序连接文件,例如首先添加 1.js,然后在其后添加 2.js 所以我按顺序编写了文件,但这种方式也不起作用 –

最佳答案

如果您想继续使用 grunt-contrib-concat,并手动明确指定您的来源,就像您拥有它应该工作的那样。您看到的模块的顺序是什么?您是否删除了 uglify 选项并只使用了 concat 选项?这个 grunt 配置正确地将组合脚本按顺序排列。

module.exports = function(grunt) {
// 1. All configuration goes here
  grunt.initConfig({




    // 1 - this is contecnate js files call them in one file only
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['a.js','b.js'],
        dest: 'built.js',
      },
    }
  });

  // end 1 - this is contecnate js files call them in one file only
// 3. Where we tell Grunt we plan to use this plug-in.
  grunt.loadNpmTasks('grunt-contrib-concat');


  // 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
  grunt.registerTask('default', ['concat']);

}

这会产生这样的结果 -

(function(){
    console.log("module a");
})();
;(function(){
    console.log("module b");
})();

此外,仅出于样式考虑,我认为不需要分号分隔符。另一条未经请求的建议如果您确实需要在 JS 文件中指定依赖顺序,您应该转向使用像 RequireJS 这样的模块加载器。 , Browserify ,或ES6 Modules (使用某种转译器)

关于javascript - 使用 grunt 按顺序连接文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27454688/

相关文章:

jquery - 在 Rails 中使用 Twitter Bootstrap Modal 时,“show”事件不会在 IE9 中触发

选择框的 javascript 函数不起作用

javascript - 超出 Grunt CSS minifier 调用堆栈

node.js - grunt 插件 grunt-contrib-haml 无法处理 UTF-8 符号

node.js - 咕噜声 : command not found

javascript - 设置 AMCharts ScrollBar 的初始范围

javascript - tween.js 和 Three.js 的未对齐平滑旋转

javascript - 在函数中使用 let 而不是 var 的优点

javascript - 如何在顺风CSS中的条件上添加样式

javascript - 将元素及其子元素从一个页面复制或保存和检索到另一个页面的方法?