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

推荐订阅源

F
Full Disclosure
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
Y
Y Combinator Blog
Cloudbric
Cloudbric
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Schneier on Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
C
Cybersecurity and Infrastructure Security Agency CISA
TaoSecurity Blog
TaoSecurity Blog
Security Latest
Security Latest
N
News and Events Feed by Topic
Hacker News - Newest:
Hacker News - Newest: "LLM"
D
DataBreaches.Net
Security Archives - TechRepublic
Security Archives - TechRepublic
H
Hacker News: Front Page
C
Cisco Blogs
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V
Vulnerabilities – Threatpost
L
LINUX DO - 最新话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
A
About on SuperTechFans
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Jina AI
Jina AI
C
CXSECURITY Database RSS Feed - CXSecurity.com
Schneier on Security
Schneier on Security
T
Tenable Blog
N
News and Events Feed by Topic
W
WeLiveSecurity
有赞技术团队
有赞技术团队
AI
AI
爱范儿
爱范儿
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
T
The Blog of Author Tim Ferriss
S
Security Affairs
Know Your Adversary
Know Your Adversary
Simon Willison's Weblog
Simon Willison's Weblog
G
GRAHAM CLULEY
Google DeepMind News
Google DeepMind News
The Cloudflare 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.