gpt4 book ai didi

gruntjs - 如何让 grunt.file.readJSON() 等待另一个任务生成文件

转载 作者:行者123 更新时间:2023-12-02 15:23:19 25 4
gpt4 key购买 nike

我正在努力设置一系列与 RequireJS r.js 编译器一起使用的 grunt 任务:1) 生成一个 .json 文件,列出目录中的所有文件2)从文件名中删除“.js”(requirejs需要这个)3)使用 grunt.file.readJSON() 解析该文件并在我的 requirejs 编译任务中用作配置选项。

这是我的 gruntfile.js 中的相关代码:

module.exports = function (grunt) {
grunt.initConfig({
// create automatic list of all js code modules for requirejs to build
fileslist: {
modules: {
dest: 'content/js/auto-modules.json',
includes: ['**/*.js', '!app.js', '!libs/*'],
base: 'content/js',
itemTemplate: '\t{' +
'\n\t\t"name": "<%= File %>",' +
'\n\t\t"exclude": ["main"]' +
'\n\t}',
itemSeparator: ',\n',
listTemplate: '[' +
'\n\t<%= items %>\n' +
'\n]'
}
},
// remove .js from filenames in module list
replace: {
nodotjs: {
src: ['content/js/auto-modules.json'],
overwrite: true,
replacements: [
{ from: ".js", to: "" }
]
}
},
// do the requirejs bundling & minification
requirejs: {
compile: {
options: {
appDir: 'content/js',
baseUrl: '.',
mainConfigFile: 'content/js/app.js',
dir: 'content/js-build',
modules: grunt.file.readJSON('content/js/auto-modules.json'),
paths: {
jquery: "empty:",
modernizr: "empty:"
},
generateSourceMaps: true,
optimize: "uglify2",
preserveLicenseComments: false,
//findNestedDependencies: true,
wrapShim: true
}
}
}
});
grunt.loadNpmTasks('grunt-fileslist');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-contrib-requirejs');

grunt.registerTask('default', ['fileslist','replace', 'requirejs']);

我遇到了一个问题,如果加载我的配置文件时“content/js/auto-modules.json”文件不存在,则 file.readJSON() 会在文件存在,整个任务失败并抛出“错误:无法读取文件”如果文件已经存在,则一切正常。

如何进行设置,以便任务配置等待在第一个任务中创建该文件,并在第二个任务中修改该文件,然后再尝试为第三个任务加载和解析其中的 JSON?或者是否有另一种方法(可能使用不同的插件)在一个任务中生成 json 对象,然后将该对象传递给另一个任务?

最佳答案

旧帖子,但我有类似的经历。

我试图加载一些 json 配置,例如:

conf: grunt.file.readJSON('conf.json'),

但是如果这个文件不存在,那么它将落入堆中并且不执行任何操作。

因此,我执行了以下操作来加载它并填充默认值(如果它不存在):

    grunt.registerTask('checkConf', 'ensure conf.json is present', function(){
var conf = {};

try{
conf = grunt.file.readJSON('./conf.json');
} catch (e){
conf.foo = "";
conf.bar = "";
grunt.file.write("./conf.json", JSON.stringify(conf) );
}

grunt.config.set('conf', conf);

});

您可能仍然遇到一些计时问题,但此方法可能会帮助遇到 readJSON 错误的人。

关于gruntjs - 如何让 grunt.file.readJSON() 等待另一个任务生成文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25434471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com