Skip to content
Please note that GitHub no longer supports Internet Explorer.

We recommend upgrading to the latest Microsoft Edge, Google Chrome, or Firefox.

Learn more

Instantly share code, notes, and snippets.

@daviferreira daviferreira/compiler.js
Last active Apr 18, 2017

Embed
What would you like to do?
Mocha compiler for es6 + react components with css require statements
'use strict';
var babel = require('babel-core');
var fs = require('fs');
// borrowed from https://github.com/babel/babel-jest/blob/master/index.js
require.extensions['.jsx'] = function (module, filename) {
var src = fs.readFileSync(filename, 'utf8');
// Allow the stage to be configured by an environment
// variable, but use Babel's default stage (2) if
// no environment variable is specified.
var stage = process.env.BABEL_JEST_STAGE || 2;
// Ignore all files within node_modules
if (filename.indexOf('node_modules') === -1 && babel.canCompile(filename)) {
var compiled = babel.transform(src, { filename: filename, stage: stage }).code;
return module._compile(compiled, filename);
}
return module;
};
require.extensions['.scss'] = function () {
return null;
};
require.extensions['.css'] = function () {
return null;
};
@daviferreira

This comment has been minimized.

Copy link
Owner Author

daviferreira commented Apr 25, 2015

mocha --reporter spec --compilers jsx:client/test/compiler.js ./client/components/**/*test.jsx

@xseignard

This comment has been minimized.

Copy link

xseignard commented Dec 6, 2015

Nice, instead of embedding the babel compiler you could do something like this

null-compiler.js

function noop() { return null; }

require.extensions['.css'] = noop;
require.extensions['.md'] = noop;

And run mocha like this:

mocha test/**/*.test.js* -R spec --compilers css:./test/misc/null-compiler,jsx:babel-core/register --recursive

@adriancooney

This comment has been minimized.

Copy link

adriancooney commented Jan 31, 2016

Thanks for this!

@aweber1

This comment has been minimized.

Copy link

aweber1 commented Feb 2, 2016

Thanks for sharing this!

@ramirotw

This comment has been minimized.

Copy link

ramirotw commented Feb 2, 2016

👍 thanks!!

@hammeiam

This comment has been minimized.

Copy link

hammeiam commented Feb 21, 2016

@xseignard this is a great solution! I changed your answer from css to less to suit my purposes and interestingly, I kept getting Invariant Violation errors until I switched the order of the compilers and listed jsx first. Any idea why that would be?

@AlastairTaft

This comment has been minimized.

Copy link

AlastairTaft commented Jul 11, 2016

Brilliant! Thanks

@manuelro

This comment has been minimized.

Copy link

manuelro commented Apr 18, 2017

babel.canCompile is not a function on babel-core: ^6.24.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.