How do I await a piece of code within weback config?

Viewed 2627

I have an async function that returns a set of webpack entries, I'd like to use async / await to get the entry property from the function but because of webpack.config.js module.export of a plain object I can't execute any top-level await and return a plain object.

Here's what I mean:

const myFunc = require('./something');
const entry = await myFunc(__dirname);
module.exports = {
    entry,
    "mode": "development",
    "output": {
        "path": __dirname+'/static',
        "filename": "[name].[chunkhash:8].js"
    }
}

Of course I understand that top-level wait is not possible, however, I need module.export to export a promise instead of this plain object. Is this possible within webpack?

3 Answers

You can try using webpack 4. I believe you can assign an asynchronous function returning a json object to you module.exports instead of a plain json object. Try adding the below code in your webpack.config.js

I am using webpack 4.1.1 and it works fine for me.

const doAsync = async () => {
    const myFunc = require('./something');
    const entry = await myFunc(__dirname);
    return {
        entry,
        'mode': 'none',
        'output': {
            'path': __dirname + '/static',
            'filename': '[name]'
        }
    };
};
module.exports = doAsync;

I dealt with this in UNIX the following way:

export ENTRY=$(yarn --silent ts-node ./riddance.run.ts ../LAST_STAND)
yarn webpack

and

const entry = JSON.parse(process.env.ENTRY);

module.exports = {
    entry,
    "mode": "none",
    "output": {
        "path": __dirname+'/static',
        "filename": "[name]"
    }
}

roshan092’s answer is almost complete, for me it's works with a invocation after doAsync, like this:

const doAsync = async () => {
  const myFunc = require('./something');
  const entry = await myFunc(__dirname);
  return {
    entry,
    'mode': 'none',
    'output': {
        'path': __dirname + '/static',
        'filename': '[name]'
    }
  };
};
module.exports = doAsync(); // here the invocation
Related