Provide module definition in webpack config

597 Views Asked by At

I am calling webpack programmatically. At the time that I call it, I have a settings object that I would like to include as a module in webpack. Is this possible?

I'm looking for something similar to the DefinePlugin, but I would like to define a module, not free variables.

My app code,app.js, looks like this:

var settings = require('settings');
console.log('Build number is', settings.buildNumber);

My webpack runner, webpack-runner.js:

var settings = {
  buildNumber: 100
};

// Can I pass settings into webpack config such that
// app.js will be able to access it with require('settings')?

var config = {
  entry: "./app.js",
  output: {
    path: __dirname,
    filename: "build.js"
  }
};

webpack(config, function(err, stats) {
  console.log(stats.toString());
});

Currently, the only way I have found to do this is to save my settings to a file, and then set an alias to the path of the file. But I would like to avoid saving a file only to have webpack open it a moment later.

1

There are 1 best solutions below

3
On

Yes, just require in your settings file. Example below.

// settings.js
module.exports = {
  buildNumber: 100
};

// webpack.config.js
var settings = require('./settings'); // settings.buildNumber => 100

var config = {
  entry: './entry.js',
  output: {
    path: __dirname,
    filename: 'build.js'
  }
};

webpack(config, function( err, stats ) {
  console.log(stats.toString({
    colors: true,
    modules: true,
    chunkModules: true
  }));
});