使用自定义命令运行webpack

时间:2017-01-25 08:47:14

标签: webpack bundler

有没有办法以不同的方式运行webpack来构建文件。我的意思是,例如我的目录:

src/
   A/
    css/
    js/
      index.js
   B/
    css/
    js/
      index.js
dist/
   A/
    bundle.js
   B/
    bundle.js

是否有这样的方法来配置webpack并使webpack A之类的命令仅构建A文件并将其输出到dist/Awebpack B以构建B文件。这就像gulp.task方式。

1 个答案:

答案 0 :(得分:0)

在webpack配置中,您可以使用名称bundler标记[name]

entry: {
    a: [
       path.resolve(__dirname, './a/js/index')
    ],
    b: [
       path.resolve(__dirname, './b/js/index')
    ]
},
target: 'web',
output: {
    path: __dirname + '/dist/[name]',
    publicPath: '/',
    filename: '[name].bundle.js'
},

您可以拆分配置,这样您就可以:

webpack.a.config.js:

entry: {
    a: [
       path.resolve(__dirname, './a/js/index')
    ]
},
target: 'web',
output: {
    path: __dirname + '/dist/[name]',
    publicPath: '/',
    filename: '[name].bundle.js'
},

webpack.b.config.js:

entry: {
    b: [
       path.resolve(__dirname, './b/js/index')
    ]
},
target: 'web',
output: {
    path: __dirname + '/dist/[name]',
    publicPath: '/',
    filename: '[name].bundle.js'
},

在你的gulp文件中你可以这样做:

var gulp = require('gulp');
var webpack = require('webpack-stream');

gulp.task('build:a', function() {
    return gulp.src('src/entry.js')
               .pipe(webpack( require('./webpack.a.config.js') ))
               .pipe(gulp.dest('dist/a/'));
});

gulp.task('build:b', function() {
    return gulp.src('src/entry.js')
               .pipe(webpack( require('./webpack.b.config.js') ))
               .pipe(gulp.dest('dist/b/'));
});

取自usage with gulp

你应该能够跑:

gulp build:a
gulp build:b

分享webpack配置

要分享配置,您将是webpack.base.config.js和其他两个j。

然后你可以做一个简单的Object.assign将它们合并到gulp中:

var gulp = require('gulp');
var webpack = require('webpack-stream');

var a = require('./webpack.a.config.js');
var b = require('./webpack.b.config.js');
var base = require('./webpack.base.config.js');

gulp.task('build:a', function() {
    var fullConfig = Object.assign({}, base, a);

    return gulp.src('src/entry.js')
               .pipe(webpack(fullConfig))
               .pipe(gulp.dest('dist/a/'));
});

gulp.task('build:b', function() {
    var fullConfig = Object.assign({}, base, b);

    return gulp.src('src/entry.js')
               .pipe(webpack(fullConfig ))
               .pipe(gulp.dest('dist/b/'));
});