Search code examples
javascriptinternet-explorerinternet-explorer-11babeljsbabel-polyfill

Converting a JavaScript file with Babel for use in IE11


I have a JavaScript file mystuff.js which throws errors in IE11 (due to for..of loops, etc).

So I try to convert it with Babel for use in IE11. However the output from Babel does not seem to be IE11-compatible. (IE complains "SCRIPT5009: 'require' is undefined".)

It looks like the result of Babel is not really JavaScript for IE11...


For reference here the steps I did:

  1. I install

     yarn add -D @babel/core @babel/cli @babel/preset-env
     yarn add @babel/polyfill
    
  2. I create a babel.config.json with the following content:

{
  "presets": [
    [
      "@babel/env",
      {
        "targets": {
          "edge": "17",
          "firefox": "60",
          "chrome": "67",
          "safari": "11.1",
            "ie": "11"
        },
        "useBuiltIns": "usage",
        "corejs": "3.6.4",
      }
    ]
  ]
}
  1. I have my JavaScript file in src so I run

     yarn babel src --out-dir lib
    
  2. I create a new HTML file from my old HTML file so that it loads the JavaScript from lib instead of src:

     <div id = "info">...</div>
     <script src="./lib/mystuff.js"></script>
    
  3. I serve and view the HTMLfile in IE11, but get the aforementioned error in IE's console.


Solution

  • "require" is commonjs module import function and is not available in browsers api (only nodejs) , you can use attribute type='module' on script tag AND ES6 module imports but it only works in newer browsers. Otherwise if you use imports in source code and want to ship the code to older browsers you need to use bundlers such as webpack, rollup, or parcel( way easier to setup than webpack ), Babel only polyfills javascript but does not bundles modules.

    You also need to make sure babel does not transforms ES6 modules to commonjs modules (https://babeljs.io/docs/en/babel-preset-env#modules) because commonjs is not supported in browsers as i said before