适配IE 11:修复转译后仍失效的Async/Await搜索功能
Hey, I feel your pain with IE11—it's always the odd one out when it comes to modern JS support. You’ve already tackled arrow functions, but async/await is trickier because transpiling it doesn’t just rewrite syntax—it relies on runtime features IE11 doesn’t have built-in. Let’s break down the problem and fix it step by step:
1. Your Babel Setup Is Missing Critical Runtime Support
The transform-async-to-generator plugin converts async functions to generators, but IE11 doesn’t understand generators or the regeneratorRuntime object that powers them. Instead of using this plugin alone, switch to @babel/preset-env with polyfill support—it’s far more reliable for targeting older browsers.
Update Your Babel Config
Create or modify your babel.config.json (or .babelrc) to look like this:
{ "presets": [ [ "@babel/preset-env", { "targets": { "ie": "11" }, "useBuiltIns": "usage", "corejs": 3 } ] ] }
@babel/preset-envautomatically picks the right plugins based on your target browser.useBuiltIns: "usage"injects only the polyfills your code actually needs (no unnecessary bloat).corejs: 3ensures you get polyfills for generators, Promises, and other missing APIs IE11 lacks.
2. Install Required Dependencies
Run this in your project root to get the necessary packages:
npm install @babel/core @babel/preset-env core-js@3 --save-dev
3. Don’t Forget the Promise Polyfill
Async/await depends entirely on Promises, and IE11 has zero native Promise support. The config above should handle this automatically, but if you’re still seeing errors like Promise is undefined, manually add polyfills to your app’s entry point (e.g., index.js):
import 'core-js/stable'; import 'regenerator-runtime/runtime';
4. If You Prefer Manual Rewriting (No Babel)
If you want to skip transpilation entirely, rewrite your async/await code to use Promise chains. For example, if your original async function was:
async function search(keyword) { const res = await fetch('/api/search', { method: 'POST', body: keyword }); const data = await res.json(); displayResults(data); }
Rewrite it to IE11-compatible code:
function search(keyword) { fetch('/api/search', { method: 'POST', body: keyword }) .then(function(res) { return res.json(); }) .then(function(data) { displayResults(data); }) .catch(function(err) { console.error('Search failed:', err); }); }
⚠️ Note: IE11 also doesn’t support fetch, so add the whatwg-fetch polyfill:
npm install whatwg-fetch --save
Then import it in your entry file:
import 'whatwg-fetch';
5. Test Like You Mean It
- Clear IE11’s cache (it loves hanging onto old, untranspiled code).
- Open the F12 DevTools console—look for errors like
regeneratorRuntime is not definedorPromise is undefinedto pinpoint exactly what’s missing.
Follow these steps, and your search function should work in IE11 just like it does in modern browsers.
内容的提问来源于stack exchange,提问作者Olasunkanmi

