Webpack output file to have exports default instead of module.exports

Viewed 1643

I have a case where I need webpack to create a file using export syntax and not module.exports. Is this possible?

Here's my config:

const path = require('path');

module.exports = {
  mode: "production",
  entry: "./node/example.js",
  node: {
    console: true,
    global: true,
    process: true,
    __filename: true,
    __dirname: true,
    Buffer: true,
    setImmediate: true,
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'example.js',
    libraryTarget: 'commonjs-module'
  },
  resolve: {
    // options for resolving module requests
    // (does not apply to resolving to loaders)
    modules: [
      "node_modules",
      path.resolve(__dirname, "app")
    ],
    // directories where to look for modules
    extensions: [".js", ".ts", ".jsx", ".css"],
  },

  target: "node", // enum  // the environment in which the bundle should run

}

example.js looks like this:

module.exports = function() {
  return 'hello world';
}

What I need webpack to do is export with export default rather then module.exports =.

1 Answers

You can use a transpiler (like Babel) to allow you to use language features that aren't supported by your runtime environment (like import and export syntax). You can install the required modules with

npm i @babel/core @babel/preset-env babel-loader

That installs the Babel core, a plugin which transpiles future language features, and the webpack loader to pre-process JS files with Babel.

Then, you'll need a .babelrc config file in your root project directory. In this case it just needs to contain the following

{"presets": ["@babel/preset-env"]}

That tells Babel you want to use the "preset env." plugin to transpile your import and export statements, among other things.

Finally, you need to tell Webpack to use Babel to load JS files. You can do this by adding a module.rules list to your Webpack config like so.

node: { /* ... */ },
module: {
    rules: [
        {test: /\.js$/, use: 'babel-loader'}
    ]
}
Related