diff --git a/README.md b/README.md index a88a9e6..5531f3a 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ If you want to use a different extension, do: `require('node-jsx').install({extension: '.jsx'})` +If you want to define specific paths where files are located, for optimization reasons, do: + +`require('node-jsx').install({paths: [path.resolve(__dirname, 'app')]})` + If you want to couple with an additional transform (such as CoffeeScript), do: ``` diff --git a/index.js b/index.js index 1b19b6a..dde6446 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,6 @@ var fs = require('fs'); var jstransform = require('jstransform/simple'); +var path = require('path'); var installed = false; @@ -10,22 +11,37 @@ function install(options) { options = options || {}; + // Check if module being loaded is in a path + var isInPaths = function (paths, filename) { + return !!paths.filter(function (path) { + return filename.indexOf(path) === 0; + }).length; + }; + // Import everything in the transformer codepath before we add the import hook jstransform.transform('', options); require.extensions[options.extension || '.js'] = function(module, filename) { + + var src = fs.readFileSync(filename, {encoding: 'utf8'}); + + if (options.paths && !isInPaths(options.paths, filename)) { + return module._compile(src, filename); + } + if (!options.hasOwnProperty("react")) options.react = true; - var src = fs.readFileSync(filename, {encoding: 'utf8'}); if (typeof options.additionalTransform == 'function') { src = options.additionalTransform(src); } + try { src = jstransform.transform(src, options).code; } catch (e) { throw new Error('Error transforming ' + filename + ' to JS: ' + e.toString()); } + module._compile(src, filename); }; diff --git a/node-jsx-path-invalid.spec.js b/node-jsx-path-invalid.spec.js new file mode 100644 index 0000000..5862452 --- /dev/null +++ b/node-jsx-path-invalid.spec.js @@ -0,0 +1,8 @@ +describe('node-jsx', function() { + it('should not work on wrong paths passed', function() { + require('./index').install({ + paths: ['somepath'] + }); + expect(require.bind(null, './test-module')).toThrow(); + }); +}); diff --git a/node-jsx-path-valid.spec.js b/node-jsx-path-valid.spec.js new file mode 100644 index 0000000..b7ddef4 --- /dev/null +++ b/node-jsx-path-valid.spec.js @@ -0,0 +1,10 @@ +var path = require('path'); + +describe('node-jsx', function() { + it('should work only on paths passed', function() { + require('./index').install({ + paths: [__dirname] + }); + expect(require('./test-module').indexOf('data-reactid')).toBeGreaterThan(-1); + }); +}); diff --git a/package.json b/package.json index e52aa4e..b4d49fb 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "react": "^0.13.2" }, "scripts": { - "test": "jasmine-node node-jsx.spec.js" + "test": "jasmine-node node-jsx.spec.js && jasmine-node node-jsx-path-valid.spec.js && jasmine-node node-jsx-path-invalid.spec.js" }, "repository": "petehunt/node-jsx", "author": "Pete Hunt",