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

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | 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
Write your own code transform for fun and profit
2018-06-04 · via Kent C. Dodds Blog

If you haven't heard, babel-plugin-macros "enables zero-config, importable babel plugins." A few months ago, I published a blog post about it on the official babel blog: "Zero-config code transformation with babel-plugin-macros".

Since then, there have been a few exciting developments:

  1. You can use it with a create-react-app application (v2 beta) because it's now included by default in the beta version of babel-preset-react-app (which is what create-react-app v2 beta is using!)
  2. It was added as an optional transform to astexplorer.net by @FWeinb

Up until now, only early adopters have tried to write a macro, though there are a fair amount of people using the growing list of existing macros. There are tons of awesome things you can do with babel-plugin-macros, and I want to dedicate this newsletter to showing you how to get started playing around with writing your own.

Let's start off with a contrived macro that can split a string of text and replace every space with 🐶. We'll call it gemmafy because my dog's name is "Gemma." Woof!

  1. Go to astexplorer.net
  2. Make sure the language is set to JavaScript
  3. Make sure the parser is set to babylon7
  4. Enable the transform and set it to babel-macros (or babel-plugin-macros as soon as this is merged)

Then copy/paste this in the source (top left) code panel:

import gemmafy from 'gemmafy.macro'

console.log(gemmafy('hello world'))

And copy/paste this in the transform (bottom left) code panel:

module.exports = createMacro(gemmafyMacro)

function gemmafyMacro({ references, state, babel }) {
	references.default.forEach((referencePath) => {
		const [firstArgumentPath] = referencePath.parentPath.get('arguments')
		const stringValue = firstArgumentPath.node.value
		const gemmafied = stringValue.split(' ').join(' 🐶 ')
		const gemmafyFunctionCallPath = firstArgumentPath.parentPath
		const gemmafiedStringLiteralNode = babel.types.stringLiteral(gemmafied)
		gemmafyFunctionCallPath.replaceWith(gemmafiedStringLiteralNode)
	})
}

Alternatively, you can open this

TADA 🎉! You've written your (probably) very first babel plugin via a macro!

Here's the output that you should be seeing (in the bottom right panel):

console.log('hello 🐶 world')

You'll notice that babel-plugin-macros will take care of removing the import at the top of the file for you, and our macro replaced the gemmafy call with the string.

So here's your challenge. Try to add this:

console.log(gemmafy('hello world', 'world goodbye'))

Right now that'll transpile to:

console.log('hello 🐶 world')

Your job is to make it do this instead:

console.log('hello 🐶 world', 'goodbye 🐶 world')

From there, you can play around with it and do a lot of fun things!

If you want to see more of the capabilities, then copy this in the source (top left):

import myMacro, { JSXMacro } from 'AnyNameThatEndsIn.macro'
// (note: in reality, the AnyNameThatEndsIn.macro should be the name of your package
// for example: `codegen.macro`)
const functionCall = myMacro('Awesome')
const jsx = <JSXMacro cool="right!?">Hi!</JSXMacro>
const templateLiteral = myMacro`hi ${'there'}`
literallyAnythingWorks(myMacro)

And copy/paste this in the transform (bottom left) code panel:

module.exports = createMacro(myMacro)

function myMacro({ references, state, babel }) {
	// `state` is the second argument you're passed to a visitor in a
	// normal babel plugin. `babel` is the `@babel/core` module.
	// do whatever you like to the AST paths you find in `references`.
	// open up the console to see what's logged and start playing around!

	// references.default refers to the default import (`myMacro` above)
	// references.JSXMacro refers to the named import of `JSXMacro`
	const { JSXMacro = [], default: defaultImport = [] } = references

	defaultImport.forEach((referencePath) => {
		if (referencePath.parentPath.type === 'TaggedTemplateExpression') {
			console.log(
				'template literal contents',
				referencePath.parentPath.get('quasi'),
			)
		} else if (referencePath.parentPath.type === 'CallExpression') {
			if (referencePath === referencePath.parentPath.get('callee')) {
				console.log(
					'function call arguments (as callee)',
					referencePath.parentPath.get('arguments'),
				)
			} else if (
				referencePath.parentPath.get('arguments').includes(referencePath)
			) {
				console.log(
					'function call arguments (as argument)',
					referencePath.parentPath.get('arguments'),
				)
			}
		} else {
			// throw a helpful error message or something :)
		}
	})

	JSXMacro.forEach((referencePath) => {
		if (referencePath.parentPath.type === 'JSXOpeningElement') {
			console.log('jsx props', {
				attributes: referencePath.parentPath.get('attributes'),
				children: referencePath.parentPath.parentPath.get('children'),
			})
		} else {
			// throw a helpful error message or something :)
		}
	})
}

Next, open up your developer console and check out the console logs. Have fun with that!

Alternatively, you can just go here

Conclusion

I think there are a LOT of really cool places we can go with this technology. I didn't spend any time in this newsletter talking about the why behind macros or giving you ideas. I'll link to some resources for ideas below. The basic idea is if there's a way that you can pre-compile some of your operations, then you can improve runtime performance/bundle size of your application. In addition, this allows you to do some things at build time when you have access to the file system. The possibilities are really endless and we're just getting started! Enjoy!