关于'进入'的Grunt-webpack通配符

时间:2014-02-27 19:26:25

标签: javascript node.js gruntjs

我正在使用Grunt来编译页面级JS资产。

    webpack: {
        build: {
            entry: {
                // Add your page JS here!
                home: "./assets/scripts/tmp/Pages/home.js",
                events: "./assets/scripts/tmp/Pages/events.js"
            },
            output: {
                path: "./public/scripts"
            }
        }
    }

这就是我目前正在做的事情,但我想做的事情如下:

    webpack: {
        build: {
            entry: "./assets/scripts/tmp/Pages/*",
            output: {
                path: "./public/scripts"
            }
        }
    }

但是,如果“找不到输入模块中的错误:”错误,则会失败。

我尝试过SRC和DEST选项,但他们似乎甚至没有编译文件:S

提前致谢

3 个答案:

答案 0 :(得分:3)

entry选项不支持通配符,但grunt支持。您可以使用grunts通配符支持为entry选项构建对象:

var pagesBase = path.resolve("assets/scripts/tmp/Pages");

build: {
  entry: grunt.file.expand({ cwd: pagesBase }, "*").reduce(function(map, page) {
    map[path.basename(page)] = path.join(pagesBase, page);
    return map;
  }, {}),
  output: {
    path: "./public/scripts",
    filename: "[name].js" // You also need this to name the output file
  }
}

grunt.file.expand只返回pages目录中所有匹配文件的数组。 Array.prototype.reduce用于将数组转换为对象。

注意:要完成示例,您还需要在[name]选项中添加output.filename

答案 1 :(得分:0)

对于寻找简单事实的其他人......这就是我所使用的:

webpack: {
    build: {
        entry: {
            "home-page": "./" + path + "scripts/tmp/Pages/home-page.js",
            "event-page": "./" + path + "scripts/tmp/Pages/event-page.js",
            "performer-page": "./" + path + "scripts/tmp/Pages/performer-page.js",
            "order-page": "./" + path + "scripts/tmp/Pages/order-page.js",
            "support-page": "./" + path + "scripts/tmp/Pages/support-page.js"
        },
        output: {
            path: "public/scripts",
            filename: "[name].js"
        }
    }
}

答案 2 :(得分:0)

类似于Tobias K.回答,但有一个工作的例子:

var config = {
  ...
  webpackFiles: {}
};

//Dynamically create list of files in a folder to bundle for webpack
grunt.file.expand({ cwd: 'my/folder/' }, "*").forEach(function(item){
  config.webpackFiles[item.substr(0,item.indexOf('.js'))] = './my/folder/' + item;
});

然后在你的笨拙的任务中使用它:

webpack: {
  build: {
    entry: config.webpackFiles,
    output: {
      path: "<%= config.jsDest %>/",
      filename: "[name].js"
    },
    module: {
     ...
    }
  }
},

唯一的缺点是,如果你想在这个版本中添加特定文件(例如bundle app.js),你必须将它添加到webpackFiles变量中,如此

//Dynamically create list of view to bundle for webpack
config.webpackFiles.App = './' + config.jsSrc + '/App.js';
grunt.file.expand({ cwd: 'Static/js/src/views/' }, "*").forEach(function(item){
  config.webpackFiles[item.substr(0,item.indexOf('.js'))] = './Static/js/src/views/' + item;
});