Skip to content

Instantly share code, notes, and snippets.

@aaronmccall
Created January 4, 2017 22:21
Show Gist options
  • Save aaronmccall/a2401ec7767366c76fa41ef00ade027f to your computer and use it in GitHub Desktop.
Save aaronmccall/a2401ec7767366c76fa41ef00ade027f to your computer and use it in GitHub Desktop.
How to replace coffee-react in your project

Motivation

Have you been using coffee-react or coffee-jsx-loader (or both), and you've started getting a lot of deprecation warnings or errors?

Assumptions

In our project, we were using webpack with coffee

Implementation

  1. Ensure that you have coffee-script and babel-core installed as devDependencies: npm i -D coffee-script babel-core
  2. Refactor your JSX to be wrapped in backticks as seen in People.coffee here
  3. Re-configure coffeescript loading as per webpack.config.js here
  4. If needed for testing, add a coffee-react/register replacement
# Finally, ensure that all of your JSX in your components is in raw JS
import React from 'react'
export class People extends React.Component
onPersonClick: (personId) => @context.router.push("/people/#{personId}")
render: ->
{ data } = @props
`(
<div>
<h1>People</h1>
<ul>
{data.people.map((person) => (
<li onClick={this.onPersonClick.bind(this, person.id)}>{person.name}: {person.title}</li>
)}
</ul>
</div>
)`
// This module replaces coffee-react/register for your test suite
const fs = require('fs')
const coffee = require('coffee-script')
const babel = require('babel-core')
require.extensions['.coffee'] = (module, filename) => {
if (filename.indexOf('node_modules') !== -1) return module
const raw = fs.readFileSync(filename, 'utf8')
// BOM stripping code borrowed from coffee-react's coffeescript compilation
// logic. It reduces the possibility of CoffeeScript's compiler exploding.
const stripped = (raw.charCodeAt(0) === 0xFEFF) ? raw.substring(1) : raw
const jsx = coffee.compile(stripped, {
filename,
inlineMap: true
})
const js = babel.transform(jsx, { filename }).code
return module._compile(js, filename)
}
// Add this (at minimum) loader to your loaders section.
// You may need to add additional presets depending on what features you want to support in your raw JS
{
test: /\.coffee$/,
// replace loader: 'coffee-jsx-loader' with
loaders: ['babel-loader?{"presets": ["react"]}', 'coffee-loader']
// NOTE: the order above is correct; webpack runs loaders in left-to-right order
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment