Getting Error Promise is undefined in IE11

后端 未结 7 776
刺人心
刺人心 2020-12-24 11:29

I am converting React code to typescript, target in tsconfig is es5.

on running in IE 11 i get an error \"Promise is undefined\"

I know i need to polyfill,bu

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 11:39

    As of Babel 7.4.0

    ES6 Promises are just one problem you will have more such as the new assignment operator and more. There's a few things you have to do to get your React soloution working nicely for IE11

    • core-js will provide most of the pollyfills you need (although an extra one is required for fetch)
    • isomporphic-fetch - because this isn't provided by core-js
    • are-you-es5 - The common practice is to not transpile your node modules, however some modules are written in ES6 or above then they just won't work, so you can use are-you-es5 together with webpack to generarte include and exclude patterns of what and what not to transpile

    Polyfills

    According to @babel/pollyfill use core-js like this

    its important to note that @babel/pollyfill have advised to use core-js instead

    Answer used for a similar problem on SO here

    // install packages
    npm install core-js
    npm install regenerator-runtime
    npm install isomorphic-fetch
    
    // then in your entry point (index.ts or index.js)
    import "isomorphic-fetch"
    import "core-js/stable";
    import "regenerator-runtime/runtime";
    

    Configure Webpack to transpile the relevant node_moduels

    npm install are-you-es5

    in your webpack config file

    import {
      checkModules,
      buildIncludeRegexp,
      buildExcludeRegexp
    } from 'are-you-es5'
    
    const result = checkModules({
      path: '', // Automatically find up package.json from cwd
      checkAllNodeModules: true,
      ignoreBabelAndWebpackPackages: true
    })
    
    /** Returns the regexp including all es6 modules */
    const es6IncludeRegExp = buildIncludeRegexp(result.es6Modules)
    
    /** Returns the regexp excluding all es6 modules */
    const es6ExcludeRegexp = buildExcludeRegexp(result.es6Modules)
    
    
    {
      ...
      module: {
        rules: [
          {
            test: /\.(t)sx?$/,
            use: {
              loader: "babel-loader",
            },
            exclude: /node_modules/,
          },
          {
            test: /\.(j)sx?$/,
            use: {
              loader: "babel-loader",
            },
            exclude: es6ExcludeRegexp, // don't transpile these!!!
            include: es6IncludeRegExp  // tranpile these 
          }
        ]
      }
    }
    

    It took me a long time to get everything working for IE11 hopefully this will save people the pain I went through.

提交回复
热议问题