piernik
piernik

Reputation: 3657

Cannot use exported classes in webpack configuration

I need to have multiple configurations of webpack@5. I wanted to create WebpackBuilder class that will be responsible for creating that webpack configuration.

So I created that file:

export default class WebpackBuilder {
    test() {
        console.log('Test');
    }
}

When I import that file using const WebpackBuilder = require('./webpack.builder'); I got errors:

[webpack-cli] C:\strony\www\polskieszlaki_new\strony\webpack.builder.js:3
export default class WebpackBuilder {
^^^^^^

SyntaxError: Unexpected token 'export'


When using import WebpackBuilder from './webpack.builder';

[webpack-cli] C:\strony\www\polskieszlaki_new\strony\webpack.blog.config.js:2
import WebpackBuilder from './webpack.builder';
^^^^^^

SyntaxError: Cannot use import statement outside a module

My webpack command is webpack --mode=production --config webpack.blog.config.js

Upvotes: 0

Views: 149

Answers (1)

tmhao2005
tmhao2005

Reputation: 17514

Looks like you imported an esm module into your configuration file which is written in cjs style.

You have to turn your esm module to cjs:

class WebpackBuilder {
    test() {
        console.log('Test');
    }
}


module.exports = WebpackBuilder;

NOTE: You can also find out more languages to write the configuration file here: https://webpack.js.org/configuration/configuration-languages/

Upvotes: 1

Related Questions