Fixing IE11 Compatibility Problems in SPFx with Babel

I recently ran into an annoying problem in one of my SPFx solutions; while it worked perfectly in Chrome, the Web Part didn’t even load in IE11. After a bit of digging, it turned out that the “SCRIPT1002” errors I was getting were caused by one of the npm packages I was using, which used the “class” keyword – a keyword introduced by ES6 but not supported by IE11. Worse still, while there are many polyfills for ES6 features, this is not possible for the “class” keyword.

The common solution to this kind of problem is to use a transpiler; a module that compiles existing code (even inside your node_modules folder) into JavaScript readable by older browsers. Babel-loader is a pretty well-known transpiler package that works with webpack – and here’s how you get it to work in your SPFx solution:

To use babel-loader in your SPFx solution, you first have to install it;

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

Next, in your gulpfile.js, insert the following code just before the line that says build.initialze(gulp);

build.configureWebpack.mergeConfig({
  additionalConfiguration: (generatedConfiguration) => {
    generatedConfiguration.module.rules.push(
      {
        test: /\.m?js$/, use:
        {
          loader: "babel-loader",
          options:
          {
            presets: [["@babel/preset-env",
              {
                targets: {
                  "ie": "11"
                }
              }]]
          }
        }
      }
    );

    return generatedConfiguration;
  }
});

By doing this, you add an additional rule to your webpack configuration that tells the babel-loader to transpile your files into an IE11 compatible syntax.
Note that most default babel-loader configurations will add an “exclude” rule for the node_modules folder, but in this case we want Babel to transpile our npm packages since they were causing our problems.

Related Post

One Reply to “Fixing IE11 Compatibility Problems in SPFx with Babel”

Leave a Reply to Guest Cancel reply

Your email address will not be published.