我有自定义函数,当在同一个gruntfile.js中定义任务时,它们可以很好地工作,但是我的gruntfile.js现在有2000多行,并且变得难以维护。是否可以全局使用这些功能而不必在每个任务文件中再次定义它们?从外部任务中调用它们时,两个功能都不起作用。我只是得到未定义的错误功能。
我有下一个结构
gruntfile.js
grunt/tasks/functions.js
grunt/tasks/styles.js
文件内容如下:
gruntfile.js
module.exports = function(grunt) {
require('jit-grunt')(grunt)
function globalFunctionOne(param1) {
console.log('yay it works from main file');
}
grunt.initConfig({});
console.log(grunt.config());
grunt.loadTasks('grunt/tasks')
grunt.registerTask('default', ['sass:dist'];
}
functions.js
module.exports = function(grunt) {
function globalFunctionTwo(param1) {
console.log('yay it works from partial file');
}
}
styles.js
module.exports = function(grunt) {
grunt.config('sass', {
options: {
implementation: sass,
includePaths: globalFunctionOne('dev'),
outputStyle: 'expanded',
sourceMap: true
},
dist: {
files: {
globalFunctionTwo('dist'),
}
}
});
}
2,000行?那是一个很长的抱怨文件。这是一个gruntfile,您可以采用它来将您的代码分解为更具模块化的内容:
gruntfile.js
function init(grunt) {
"use strict";
function loadConfig(pattern) {
let config = {},
fileName,
fileData;
grunt.file.expand(pattern).forEach(function (filePath) {
fileName = filePath.split('/').pop().split('.')[0];
fileData = require('./' + filePath)(grunt);
config[fileName] = fileData;
});
return config;
}
function loadGrunt() {
const config = {
pkg: grunt.file.readJSON('package.json')
};
require('load-grunt-tasks')(grunt);
if (grunt.file.exists('grunt/tasks')) {
grunt.log.writeln('task directory found, loading tasks...');
grunt.loadTasks('grunt/tasks');
}
grunt.util._.extend(config, loadConfig('grunt/configs/**/*.js'));
grunt.initConfig(config);
}
loadGrunt();
}
module.exports = init;
此gruntfile的作用:
.js
中找到的每个project-root/grunt/configs
文件。名字每个文件的对应于grunt配置对象的密钥。project-root/grunt/tasks
中的所有任务如果您的配置使用grunt-contrib-copy
,那么在您的项目中,您将拥有类似于以下内容的配置文件:
project-root / grunt / configs / copy.js
module.exports = function (grunt) {
"use strict";
return {
base: {
options: {
process: function (content) {
return grunt.template.process(content);
}
},
src: 'grunt/templates/base.url.js',
dest: 'www/source/config/base.url.js'
},
pluginManifest: {
src: 'cordova/template/package.json',
dest: '<%= grunt.task.current.args[0] %>/package.json'
},
splashScreens: {
expand: true,
cwd:"grunt/templates/",
src: "screen/**",
dest: '<%= create.dest %>/res/'
}
};
};
然后,您可以将全局函数转换为helpers
javascript文件,并以典型的Node.js方式将其导入到配置中:
project-root / grunt / configs / sass.js
module.exports = function (grunt) {
const helpers = require("../helpers.js)(grunt);
return {
options: {
implementation: sass,
includePaths: helpers.globalFunctionOne('dev'),
outputStyle: 'expanded',
sourceMap: true
},
dist: {
files: {
globalFunctionTwo('dist'),
}
}
};
};
project-root / grunt / helpers.js
module.exports = function (grunt) {
function globalFunctionOne(param1) {
console.log('yay it works from main file');
}
function globalFunctionTwo(param1) {
console.log('yay it works from partial file');
}
return {
globalFunctionOne,
globalFunctionTwo
};
};