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

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

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
Misunderstanding ES6 Modules, Upgrading Babel, Tears, and a Solution
Kent C. Dodds 🏹 @kentcdodds · 2015-12-23 · via Kent C. Dodds Blog

On October 29th, 2015, Sebastian McKenzie, James Kyle, and the rest of the Babel team dropped a huge major release for frontend developers everywhere: Babel 6.0.0. It's totally awesome. No longer just a transpiler, it's now a super pluggable JavaScript tooling platform. As a community, we've only scratched the surface of what it is capable of and I'm excited (and cautiously optimistic) for what the future holds in JavaScript tooling.

All of that said, Babel 6.0.0 was an enormous breaking change. It had a bit of a rocky start. It's not entirely straightforward to upgrade and takes some learning. This post isn't going to talk about how you upgrade Babel, necessarily. I'm just going to touch on what I learned about my own code when Babel fixed a bug I relied on heavily... Here are some resources I recommend you check out before you try to upgrade your stuff from Babel 5 to Babel 6:

Clearing up the Babel 6 Ecosystem

Quick guide: how to update Babel 5.x -> 6.x

ES6 Modules

Upgrading for me would not have been that difficult if I had understood the ES6 Modules specification correctly. Babel 5 allowed misuse of export and import statements and Babel 6 fixed this problem. At first I thought this may be a bug. I asked about it on Stack Overflow and Logan Smyth informed me that I fundamentally misunderstood ES6 modules and that Babel 5 had facilitated that misunderstanding (writing a transpiler is hard).

Near-midlife crisis

At first, I didn't quite understand what Logan meant, but when I had the time to dedicate to upgrading my app, this happened

Tyler McGinnis, Josh Manders, and I went back and forth quite a bit on this thread. It's probably hard to follow, but this is when I realized that the problem wasn't exporting the object as a default, but how I expected that I could import the object.

I always assumed that I could export an object as the default and then destructure the pieces out of that object I needed, like so:

// foo.js
const foo = { baz: 42, bar: false }
export default foo

// bar.js
import { baz } from './foo'

Babel 5 allowed this because of how it transpiled the export default statement. However this is technically incorrect according to the spec which is why Babel 6 (correctly) removed that capability and effectively broke over 200 of my modules in my application at work.

I finally figured out how things really work when I reviewed Nicolás Bevacqua's blogpost

And I discovered why what I had been doing wouldn't work when I read Axel Rauschmayer's blogpost

Here's the basic idea: ES6 modules are supposed to be statically analyzable (runtime cannot change the exports/imports) so it can't be dynamic. In the example above, I could change the foo object's properties at runtime and then my import statement could import that dynamic property, like this:

// foo.js
const foo = {}
export default foo
somethingAsync().then((result) => (foo[result.key] = result.value))

// bar.js
import { foobar } from './foo'

We'll assume that result.key is 'foobar'. In CommonJS this would work just fine because the require statements happen at runtime (when they're required):

// foo.js
const foo = {}
module.exports = foo
somethingAsync().then((result) => (result) => (foo[result.key] = result.value))

// bar.js
const { foobar } = require('./foo')

However, because the ES6 specification states that imports and exports must be statically analyzable, you can't accomplish this dynamic behavior in ES6.

So that's the why for Babel's change. It's no longer possible to do this and that's a good thing.

What does this mean?

Coming up with a good way to describe this in prose has proven difficult, so I hope a bunch of code examples and comparisons will be instructive

The problem I had was I was combining ES6 exports with CommonJS require. I would do something like this:

// add.js
export default (x, y) => x + y

// bar.js
const three = require('./add')(1, 2)

With the changes that Babel made, I had three choices:

Option 1: require with default

// add.js
export default (x, y) => x + y

// bar.js
const three = require('./add').default(1, 2)

Option 2: ES6 modules 100%

// add.js
export default (x, y) => x + y

// bar.js
import add from './add'
const three = add(1, 2)

Option 3: CommonJS 100%

// add.js
module.exports = (x, y) => x + y

// bar.js
const three = require('./add')(1, 2)

How did I fix it?

After a few hours I got the build running and the tests passing. I had two different approaches for different scenarios:

  1. I changed the export to be CommonJS (module.exports) rather than ES6 (export default) so I could continue to require it as I have been doing.
  2. I did a fancy regex find and replace (should have used a codemod) to change the other require statements from require('./thing') to require('./thing').default

This worked out pretty well. The biggest challenge was just understanding how the ES6 modules spec works and how Babel transpiles it down to CommonJS so it can interoperate. Once I figured that out it was just monkey work to update my code to follow this convention.

Recommendations

Try to avoid mixing ES6 modules and CommonJS. I personally would say just go with ES6 modules for everything. One of the reasons that I mixed them in the first place was so I could do a one-liner require and immediately use the required module (like require('./add')(1, 2)). But that's really not a big enough benefit IMO.

If you feel like you must combine them, you might consider using one of the following babel plugins/presets:

babel-preset-es2015-node5

babel-plugin-add-module-exports

Conclusion

The real lesson from all of this is that we should learn how things are supposed to work. I could have saved myself a great deal of time if I had just understood how the ES6 module spec actually is intended to work.

You may benefit from this egghead.io lesson I made demonstrating how to upgrade from Babel 5 to Babel 6:

Also, remember that nobody's perfect and we're all learning here :-) See you on Twitter!


Appendix…

More examples:

Before the change with Babel, a require statement was similar to:

import add from './add'
const three = add(1, 2)

But after the change in Babel, the require statement now becomes more like:

import * as add from './add'
const three = add.default(1, 2)

What caused the problem for me was that now the add variable is no longer the default export, but an object that has all the named exports and the default export (under the default key).

Named Exports:

It's notable that you can also use named exports and I recommend this with utility modules. This will allow you to do the destructuring-like syntax in the import statement (warning, despite what it looks like it's not actually destructing due to the static analysis reasons mentioned earlier). So you could do:

// math.js
const add = (x, y) => x + y
const subtract = (x, y) => x - y
const multiply = (x, y) => x \* y
export {add, subtract, multiply}

// foo.js
import {subtract, multiply} from './math'

This gets really awesome/exciting with tree shaking.

Personally, I generally recommend that for a component (like a React component or an Angular service) you'll want to use default exports (you're importing a specific thing, single file, single component, you know 😀). But for utility modules you generally have various pure functions that can be used independently. This is a great use case for named exports.