Commit 96182bc1 authored by Kent C. Dodds's avatar Kent C. Dodds Committed by Tim Neutkens

add babel-macros example (#2563)

parent d727a6f0
{
"presets": ["react"],
"plugins": ["babel-macros"]
}
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-babel-macros)
# Example app with [babel-macros](https://github.com/kentcdodds/babel-macros)
## How to use
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-babel-macros
cd with-babel-macros
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
This example features how to configure and use [`babel-macros`](https://github.com/kentcdodds/babel-macros) which allows you
to easily add babel plugins which export themselves as a macro without needing
to configure them.
You'll notice the configuration in `.babelrc` includes the `babel-macros`
plugin, then we can use the `preval.macro` in `pages/index.js` to pre-evaluate
code at build-time. `preval.macro` is effectively transforming our code, but
we didn't have to configure it to make that happen!
Specifically what we're doing is we're prevaling the username of the user who
ran the build.
{
"name": "with-babel-macros",
"version": "1.0.0",
"description": "using next.js with babel-macros",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"author": "Kent C. Dodds <kent@doddsfamily.us> (http://kentcdodds.com/)",
"license": "MIT",
"devDependencies": {
"babel-macros": "^0.5.1",
"babel-preset-react": "^6.24.1",
"preval.macro": "^1.0.1"
}
}
import React from 'react'
import Document, {Head, Main, NextScript} from 'next/document'
export default class MyDocument extends Document {
render () {
return (
<html>
<Head>
<title>With babel-macros</title>
<style dangerouslySetInnerHTML={{__html: this.props.css}} />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
import React from 'react'
import preval from 'preval.macro'
const whoami = preval`
const userInfo = require('os').userInfo()
module.exports = userInfo.username
`
export default WhoAmI
function WhoAmI () {
return (
<div style={{display: 'flex', justifyContent: 'center'}}>
<h1>
<pre>
whoami: {whoami}
</pre>
</h1>
</div>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment