Search code examples
javascriptwebpackgulp

Apply a loader to only one file in webpack


I'm new to webpack. I have been using gulp until now and trying to migrate to webpack.

In my .gulpfile I have:

var preProcess = require('gulp-preprocess');

gulp.src('app/config/app.constants.js')
.pipe(preProcess({
  context: {
    NODE_ENV: options.env
  }
}))

I have the following lines in app/config/app.constants.js that need to be removed in production:

//@if NODE_ENV='development'
AppConstants.api = 'https://localhost:333/api';
AppConstants.webRoot = 'http://localhost:222';
//@endif

I am trying to accomplish this in wepack.config.js:

if (!isDev) {
    config.module.rules.push([
        {
            test: ???, // Can't figure out what to put here
            exclude: /(node_modules|bower_components|\.spec\.js)/,
            use: [
                {
                    loader: 'webpack-strip-block',
                    options: {
                        start: '@if NODE_ENV='development'',
                        end: '@endif'
                    }
                }]
        }
    ])
}

Two questions: How do I test for a single file? Is this the right way to replace gulp-preprocess?


Solution

  • To apply a loader to a single file, use include instead of exclude. This is whitelisting instead of blacklisting. You don't need to use test at all. For example...

    {
        include: 'path/to/your/file',
        use: [{
            loader: 'webpack-strip-block',
            options: {
                start: '@if NODE_ENV='development'',
                end: '@endif'
            }
       }]
    }