Shopify / sprockets-commoner

Use Babel in Sprockets to compile JavaScript modules for the browser
MIT License
182 stars 22 forks source link

Support Rails engines #44

Open richardvenneman opened 7 years ago

richardvenneman commented 7 years ago

I'm trying setup sprockets-commoner for use with a Rails engine. Haven't had much success so far, unfortunately as it seems the Babel transform are not getting applied.

In my engine, I have added the sprockets-commoner gem with the following .babelrc:

{
  "presets": ["es2015", "react"]
}

In my host app I also added the sprockets-commoner gem, with the samen .babelrc. I load the engine JavaScript in the host app with a javascript_include_tag. This is where I get a runtime error: SyntaxError: Unexpected keyword 'import'.

I tried loading the engine JS via 2 methods:

  1. Directly load the engine JS in the javascript_include_tag (<%= javascript_include_tag 'engine/application', 'data-turbolinks-track' => true %>). This results in the non-transpiled ES2015 code being loaded in the browser.
  2. Require the engine JS in a JavaScript file in the host app (//= require engine/application) and load that file in the javascript_include_tag instead. This results in some commoner processed code, but without Babel transforms applied (which results in the runtime syntax error on the import statement):
!function() {
var __commoner_initialize_module__ = function(f) {
  var module = {exports: {}};
  f.call(module.exports, module, module.exports);
  return module.exports;
};
var global = window;

import React from 'react';
import ReactDOM from 'react-dom';

import PhoneInput from './components/PhoneInput';

ReactDOM.render(
  <PhoneInput />,
  document.getElementById('phone-input')
);
var __commoner_module__app$assets$javascripts$engine_js = {};
}();

I was wondering if this kind of setup is actually supported.

I can setup a sample repo if you'd like.

bouk commented 7 years ago

It's not supported, commoner only works with things that are placed under the app root, not with gems.

richardvenneman commented 7 years ago

All right, thanks for clearing that up! It seems I'll still have to use browserify-rails for the engine 😀