Webpack libraryTarget: "module" generates code with `'return' outside of function`

Viewed 1596

I'm trying to output an ESM module with WebPack 5. My understanding is that this feature has been added in version 5, and is used by specifying {output: libraryTarget: 'module'}} and {experiments: {outputModule: true}}.

I believe that what I'm seeing is just a WebPack bug - perhaps related to outputModule still being experimental, but I'm not very well versed in WebPack so could easily have missed something.

I get an error 'return' outside of function. With the configuration below, this happens when I run npx webpack. If I change mode to 'development', then it generates a bundle which indeed has a return statement at the end such that attempting to use it generates a similar error at runtime.

webpack.config.js:

const path = require('path');

module.exports = {
    entry: "./index.js",
    resolve: { extensions: ['.js'] },
    //using 'production' rather than 'development' catches error earlier.
    mode: 'production',
    experiments: {
        outputModule: true
    },
    output: {
        filename: 'hello.js',
        libraryTarget: "module",
        path: path.resolve(__dirname, 'dist')
    }
}

index.js

export default function() { return 42; }

package.json

{
    "name": "webpackTest",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "webpack": "webpack",
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^5.5.1",
      "webpack-cli": "^4.2.0"
    }
}
0 Answers
Related