ERROR FIX: SyntaxError: Unexpected token 'export' in ngx-bootstrap

ERROR FIX: SyntaxError: Unexpected token 'export' in ngx-bootstrap

A common error found in most ES6 packages. Fix is here.

ngx-bootsrap error.PNG

I have been facing this problem for a very long. I use to do a workaround to bypass this. But finally, I have fixed this. So, here is the solution.

Where did I find this problem:

ngx-bootstrap

Problem:

This npm package is written in ES6 and is not being transpiled to support older environments like ES5. So, it does not understand the keyword like export or import.

Solution

To make the package compatible with our environment, we have to transpile it by ourselves. I did it using webpack and babel-loader to transpile ngx-bootstrap package.

Steps:

  1. Get your universal build ready.
  2. Install webpack and loaders packages related to babel using this command,

    npm install -D babel-loader @babel/core @babel/preset-env webpack

  3. Create a webpack configuration file webpack.config.js.
  4. Add babel-loader like this, and exclude all other packages than ngx-bootstrap.
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules\/(?!ngx-bootstrap)/
      }
    ]
  }

To understand transpilation and what's going wrong in this issue, I would recommend you to read this nice article How to transpile node modules.