惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security Affairs
L
Lohrmann on Cybersecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
WordPress大学
WordPress大学
小众软件
小众软件
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
F
Full Disclosure
S
Schneier on Security
L
LangChain Blog
MyScale Blog
MyScale Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
A
Arctic Wolf
Martin Fowler
Martin Fowler
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
Latest news
Latest news
F
Fortinet All Blogs
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode Profile a React App for Performance
What is a polyfill
2018-07-30 · via Kent C. Dodds Blog

A few weeks back I found a bug with IE where all the user saw was a blank white page. If you've been around for a while in the wonderful world of the client-side SPA, you'll probably know what was wrong without thinking twice. That's right. It was a JavaScript error before client-side rendering happened.

Considering it the bug only rears its head in Internet Explorer, my first guess is a problem with polyfills. Yep! That was it!

Uncaught TypeError: contacts.includes is not a function

But we're transpiling our code with Babel! Doesn't that mean that I can use all the latest and greatest JavaScript I want without having to worry about whether the browser supports it? Nope! Let's learn more...

Polyfills vs Code Transforms

JavaScript is constantly evolving thanks to the efforts of people in and around the TC39. Some of the evolutions rely on new syntax (like arrow functions) which allows me to do this:

const addOne = (num) => num + 1
if (addOne(2) > 2) {
	console.log('Math. Wow!')
}

Often, we can use this syntax in our source code so long as we convert it to syntax that can run in the browser (for example, by using a transpiler such as babel: example transpiled in the browser with babel-preset-env).

Some other of these new features rely on new APIs, like Array.prototype.includes which allows me to do this:

const contacts = ['Brooke', 'Becca', 'Nathan', 'Adam', 'Michael']
if (contacts.includes('Rachel')) {
	console.log('You have a Rachel!')
}

With these, if you run them through babel's env preset the includes function is not transpiled because it's not a syntax issue, but a built-in API one and babel's env preset only includes transforms for syntax transformations. You could write your own babel plugin (like this) to transform the code, but for some APIs it just wouldn't be practical because the transformed version would be significantly complex.

A polyfill is code which will make the currently running JavaScript environment support features which it does not. For example, a (imperfect) polyfill for includes might look something like this (refer to MDN for a real polyfill):

if (!Array.prototype.includes) {
	Array.prototype.includes = function includes(searchElement) {
		return this.indexOf(searchElement) !== -1
	}
}

The if statement is there to make this a "gated" polyfill. That means that if the functionality already exists, the polyfill code will not override the pre-existing behavior. You may consider this to be desirable, but it's actually the reason that includesis not called contains on String.prototype (TL;DR: some versions of mootools implemented contains in a gated fashion but the implementation is different from how includes works so the TC39 had to change the name to not break tons of websites).

The part that assigns Array.prototype.includes to a function is called "monkey-patching" 🐒 By applying this to the prototype, we're adding includes support to all arrays in the app (learn more about prototypes here). Effectively, the polyfill's job is to make it so I can use the JavaScript feature without worrying about whether it's supported by the environment in which my code is running (like IE 10 for example).

Where to get transforms and polyfills

With syntax transforms, I recommend babel-preset-env. It's actually fairly straightforward. For polyfills, the most popular one is core-js. You might also look at babel-polyfill which uses core-js and a custom regenerator runtime to support generators and async/await the way that babel transpiles it. Polyfills are sometimes referred to as "shims" and you may be interested in the js-shims by airbnb (which I've been told are more spec-compliant than core-js).

Conclusion

So what did I do to fix my IE10 bug? Well, one thing that really bugs me is that I have to ship all this code for polyfills to all browsers even if they do support these features. But a few years ago I heard of a service that was able to ship polyfills that are relevant only to the browser requesting them. I created my own endpoint that uses the module that powers that service and I'll write about that next week!

I hope this is helpful! Good luck!

P.S. You may have heard of something called a "ponyfill." Ponyfills are similar to polyfills except they don't monkey-patch, instead they're just the function by itself and allow you to call them directly. Learn more about ponyfills. In general, I'm more in favor of ponyfills, though you just can't get away from polyfills completely because often your dependencies are relying on built-ins that your browsers don't support.