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

推荐订阅源

S
Securelist
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
S
Schneier on Security
T
Troy Hunt's Blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Schneier on Security
Schneier on Security
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
Arctic Wolf
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
Webroot Blog
Webroot Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News 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
Pure Modules
Kent C. Dodds 🏹 @kentcdodds · 2018-04-30 · via Kent C. Dodds Blog

A few weeks ago, I saw this tweet from Ingvar Stepanyan, followed by this one (sadly, both tweets have since been deleted).

These tweets resonated with me because it really would make a huge difference for JavaScript engines and the performance of ES Modules. It really was a missed opportunity. There's not much we can do about it at this point (though you could simulate this with dynamic imports, but then you'd have other issues).

This made me think of something else that I feel is important and I'd like to share with you. I quote tweeted Ingvar's tweet:

I totally agree. Just because that's not the way the spec is didn't mean you can't do that yourself. I highly recommend you make your modules export functions that do things rather than do things on import. twitter.com/RReverser/status/984854567706877952

0 25

Ingvar expanded on what I mean (unknowingly I'm sure) in another thread (sadly this thread has now been deleted).

Why pure modules?

Let's explore why this is a good idea. Consider the following scenario:

// a.js
import './b'
console.log('ready')

// b.js
import { serverData } from './c'

if (!serverData.user) {
	// redirect to login
	location.assign('/login')
}

// c.js
const el = document.getElementById('server-data')
const json = el.textContent
export const serverData = JSON.parse(json)

The c.js module would need the index.html to have been rendered with something like:

<script type="application/json" id="server-data">
	{ "user": null }
</script>

I expect this code would work in production as expected. There are a few problems I have with code like this (or in general any impure modules). Before we move on it's important to realize that before the console.log('ready') line is run, all the code in b.jsand c.js has been run first.

Unknown consequences 😮

When a developer imports the a.js module, it has no way of knowing what the consequences will be. If things aren't set up properly, the developer will see a cryptic message like:

Uncaught TypeError: Cannot read property 'textContent' of null

and this because they simply imported a module.

Unnecessary operations 😐

Let's say that a.js actually only needs certain utilities that b.js exposes, and doesn't actually need anything from the c.js module to be run at all. In this scenario, those modules are doing extra work that is unneeded. Wasted effort that in some situations could be a pretty impactful depending on the circumstances.

What's especially annoying is when the wasted effort results in a cryptic error. Not only did I have to figure out what the error was all about, but I don't even need that code to run in the first place!

As a related (and very important) part of this, you cannot treeshake that unused code!

Inability to choose the order of operations 😡

What if I realize that c.js needs the JSON in the DOM and so I decide I can initialize that before c.js is required like so:

// a.js
const script = document.createElement('script')
script.setAttribute('id', 'server-data')
script.setAttribute('type', 'application/json')
document.body.appendChild(script)

import './b'
console.log('ready')

Unfortunately this wont work because (per the ES modules specification) import statements are run before any of the code of the module regardless of where they appear in the code! Luckily they are at least run in the order they appear. So to do this I would have to create a new module for my setup code and import that one first:

import './setup'
import './b'
console.log('ready')

Impact on testing 😵

It's a pretty widely accepted fact that it's easier to test pure functions than impure functions. The same applies with modules. What if I wanted to test the b.js module? I'd have to initialize the DOM before importing b.js so c.jscan be initialized properly, but then how do I test it again? I have to do weird things with the module system to re-import those modules again after initializing the DOM differently.

With jest, you have jest.resetModules() which makes this much easier, but it's still not super simple, nor is it straightforward for anyone maintaining those tests.

The Alternative

So here's how I would rewrite things to be pure (in the sense that importing modules has no side-effects, though the functions they expose are not pure themselves):

// a.js
import { init } from './b'
init()
console.log('ready')

// b.js
import { serverData, init as initC } from './c'

export function init() {
	initC()
	if (!serverData.user) {
		// redirect to login
		location.assign('/login')
	}
}

// c.js
export const serverData = {}
export function init() {
	const el = document.getElementById('server-data')
	const json = el.textContent
	Object.assign(serverData, JSON.parse(json))
}

How does this resolve the above problems?

  • Unknown consequences: We're importing the init method and calling that from both b.js and c.js, so we may not know exactly what those do without looking at the implementation, but we at least know that they're doing something. 💯
  • Unnecessary operations: If b.js exported additional utility methods, we could import those without running into any surprises. 💡
  • Inability to choose the order of operations: If we wanted to initialize the server-data in a.js then we'd just do that before calling the init method from the b.js module. ✌️
  • Impact on testing: We could easily run the initfunction from b.js in a test as many times, re-initializing the DOM before each test with exactly what we need without any trouble or hacks. 🎉

Note that the a.js module is not pure. At some point one of your modules needs to do something to kick everything off. This is the purpose the a.js module is serving. These modules should normally be very small (and often it'll be your index.js entry module).

Conclusion

Keeping your modules pure means limiting the amount of stuff they're doing at the root-level of the module. It allows you to completely avoid the issues mentioned and bring more clarity to your codebase. I hope these examples (while slightly contrived) have been helpful. Good luck!