jsx doesn't seem to transpile correctly - ruby-on-rails

I am using the react-rails gem in a Rails(4.2.7) project. This is the only modification I've made to my default Gemfile:
gem 'react-rails'
I've defined a component in a .jsx file using es6 syntax:
class Foo extends React.Component {
render () {
return (<h1>hello</h1>)
}
}
This works fine, but when I attempt to import a js module, I get an error:
import ReactTransitionGroup from 'react-addons-transition-group'
class Foo extends React.Component {
render () {
return (<h1>hello</h1>)
}
}
foo.es6.self-69f3a42….js?body=1:11 Uncaught ReferenceError: require is not defined
It seems to me that if I'm not transpiling the jsx correctly then I would be getting an error in the first case, but I'm not. I've been using jsx all day long with no issues until I tried to use import.
I've tried adding the following to my Gemfile:
gem 'sprockets-es6'
gem 'babel-transpiler'
I've tried adding this to config/environments/development.rb:
config.react.jsx_transformer_class = React::JSX::BabelTransformer
And I've tried generating the component using the rails react component generator with the --es6 flag:
rails g react:component Foo --es6
What am I missing?

So here's how I resolved my issue: since I'm using the 'react-rails' gem, the addons are available via a configuration option - I added the following to config/application.rb:
config.react.addons = true
Then in my .jsx file, instead of import, this is the syntax I used to have access to ReactTransitionGroup:
var ReactTransitionGroup = React.addons.ReactTransitionGroup
I still don't understand, but maybe someday I will, why the import statement transpiles to require which is undefined, and how that could be fixed by anything other than defining require, or transpiling to something that is defined.

Related

Uncaught ReferenceError: exports is not defined react-rails

I need to add react-rails to my rails 4 app, but it's giving me hard time to figure out.
my project uses sprockets for assets:precompilation,
this is my component:
import React from "react"
class Sidebar extends React.Component {
render() {
return (<p> hello from react </p> );
}
}
export default Sidebar;
when I load the page everything works fine, except for the react component, which is just rendered as a div in the html, and in the console I see:
Sidebar.self.js?body=1:1 Uncaught ReferenceError: exports is not defined
at Sidebar.self.js:1:23
there's an initial snippet added there:
Object.defineProperty(exports, "__esModule", {
value: true
});
That causes the problem.
I tried everything I could find:
Webpacker (but that gave way more troubles so I removed it)
installing https://github.com/TannerRogalsky/sprockets-es6
Typescript ReferenceError: exports is not defined
React uncaught reference error: exports is not defined
and more. I'm not sure what I'm doing wrong (or maybe I misused one of the solutions above?)
update
I figured that I can send babel configuration options via react-rails gem using:
Rails.application.config.react.jsx_transform_options = {
plugins: ["#babel/preset-react"],
loose: ["es6.modules"]
}
I'm not sure which plugins I should use, but this doesn't appear to be affecting a thing, except that it's not ignored, if I write something that is not recognised I do get an exception.

Import my own files into the electron renderer process

This seems really dumb, but I need help for importing some source code into the renderer process in electron:
I have an electron app:
index.html (loads window.js with a tag)
- index.js
- window.js
- useful_functions.js
In window.js, I want to import some functions from useful_functions.js, so I've tried the following:
// fails with: Uncaught SyntaxError: Unexpected identifier
import { very_useful } from './useful_functions.js';
// fails with: Uncaught ReferenceError: require is not defined
const { very_useful } = require('./useful_functions.js');
// fails with: Uncaught ReferenceError: require is not defined
require('electron').remote.require('./useful_functions.js')
I also tried the nodeIntegration flag, but that didn't help either
Note: I'm not trying to import npm modules but my own code, in an other file right next to it.
I'm looking for examples, but I only find super small samples with just the basic files. (Or huge apps like atom that would take me a while to figure out)
I don't have webpack setup for this project yet, but I'm sure there is a simpler way to do this very basic task...
Thanks for any help.
In index.html, use require() instead of loading window.js with a tag, i.e., replace:
<script src="window.js"></script>
with:
<script>require('./window.js');</script>
Then, in window.js, the following statement should work too:
const { very_useful } = require('./useful_functions.js');
Note that nodeIntegration: true is needed in the options passed to new BrowserWindow() anyway:
webPreferences:
{
nodeIntegration: true
}
See:
Node Modules
Functions and objects are added to the root of a module by
specifying additional properties on the special exports object.
Variables local to the module will be private, because the module is
wrapped in a function by Node.js (see module wrapper).
Module Wrapper
Before a module's code is executed, Node.js will wrap it with a
function wrapper that looks like the following:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});

How to migrate requiring of select2.js from sprockets to webpacker

I'm in the process of migrating a Rails 5.1.5 project, which uses CoffeeScript, from using sprockets to using webpacker. The project also uses select2.js. With sprockets, I did the following:
Install jquery-rails (jQuery is a dependency for select2).
Put select2.js code in vendor/assets/javscripts.
In application.js.coffee, add:
#= require select2
After that I was able to use select2 to in my application.js.coffee file:
$(document).on 'turbolinks:load' ->
$('select').select2
So far I've described the pretty standard way of including/using javascript libraries with sprockets.
However, with webpacker I can't make select2 work and I'm not sure why. I have two hypothesis:
I'm not importing/requiring it properly;
it doesn't find jQuery at some point of the load process;
So for jQuery, I did the following:
yarn add jquery
included in my environment.js:
const webpack = require('webpack');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}));
I've removed the jquery-rails gem, as well as #= require 'jquery' and tested that jquery works, so I guess I have correctly included it. However, I tried several ways of importing select2 (using es6 imports) and none of them worked. I tried:
import select2 from 'select2';
import select2 from 'select2/dist/js/select2'
import select2 from 'select2/dist/js/select2.js'
import 'select2/dist/js/select2.js'
I even tried to import it from the old vendor location by writing inside app/javascript/pack/application.js.coffee:
import '../../../vendor/assets/javascripts/select2'
I can confirm that the file contents is imported, as I put a console.log within the select2 file under node_modules/select2/dist/js/select.js and it did get printed. However, I also get the error TypeError: $(...).select2 is not a function when I execute $('select').select2() in the browser's dev tool console.
What am I missing or doing wrong?
P.S. I can provide much more info, but I didn't want my question to get any more bloated.
P.P.S. With my modest JS knowledge, I looked at the source code but couldn't recognize what exactly they are exporting and how am I supposed to import it.
I know this is an old post, but just in case someone else could benefit:
app/javascript/packs/application.js
...other requires...
require('select2')
window.Rails = Rails
import 'bootstrap'
...other imports...
import 'select2'
import 'select2/dist/css/select2.css'
$(document).on("turbolinks:load", () => {
$('.select2').select2()
})
My similar problem
I have stumble upon the same problem with another web component (Switchery):
I imported the component with yarn add switchery (no error)
I could import it correctly through WebPack with import 'switchery' (no error bundling the pack)
But when I was trying to use the Switchery object in the browser like they say in the doc:
var elem = document.querySelector('.js-switch');
var init = new Switchery(elem);
I would get the error: ReferenceError: Switchery is not defined
Note: I didn't want to install RequireJS as WebPack is supposed to do the same thing (and even better) nowadays.
My solution:
The problem was the webpack doesn't expose the pack-generated variables and classes in the global scope!
So to fix this, I needed to do two things:
Explicitly give a name to the imported class from Switchery:
import Switchery from 'switchery'
Use this Class only in the same JS file where the import was done
Testing hack:
If you want to try that out and "go back" to the mess that sprocket allowed, in the same file, you can expose "globally" the variable so you can use in from the browser:
import Switchery from 'switchery'
window.Switchery = Swicthery
now you can execute the switchery almost like in the example:
var init = new window.Switchery(elem);
Hope that helps...

React Rails Component is not defined

I'm trying to get the react-rails gem (version 2.1) working in my Rails 4.2.4 app. I've gone through the setup steps in the Readme and I'm using webpacker for the js preprocessing. I have a component inside of app/javascript/components/label.js that looks like this:
import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom'
export default class Label extends PureComponent {
render () {
return (
<div>Something rendered in React</div>
)
}
}
And then I reference this in my view with the following line:
= react_component("Label")
As far as I can see from the Readme, this should be all that is necessary in order to render the component (provided the application pack is included in the layout, which it is)
= javascript_pack_tag 'application'
So I'm confused as to why I'm getting the error in my browser that the component is not defined.
Uncaught ReferenceError: Label is not defined
Opening app/javascript/packs/application.js I can see the following:
console.log('Hello World from Webpacker')
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true)
var ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)
First I verified that the console log is displayed in the browser (it is). I'm not sure what componentRequireContext does, but if it is relative to the current file, then it seems odd that it points to components and not ../components, but changing this doesn't render the component. However, I can get the component rendering if I add the following line:
window.Label = require('../components/label.js');
I thought the React Rails gem took care of this though, provided the components were saved in the app/javascript/components directory? There's nothing in the Readme that says that I need to explicitly declare and require the component, or am I mistaken?
It looks like you have a capitalization issue. You named the file 'label.js' but you are looking for '= react_component("Label")' So it looks and doesn't find what Label is. Then when you set Label on the window then react is like "Oh ok, Label is actually label.js." and it does stuff. TLDR capitalization matters.

Using 'material-ui' with react-rails gem?

I would like to use the material-ui component library in my Rails 4 app. I am currently using the react-rails gem to add .jsx compilation to the asset pipeline. I have added material-ui via rails-assets in the gemfile like so:
source 'https://rails-assets.org' do
gem 'rails-assets-material-ui'
end
And I have required the library in my application.js file like so:
//= require material-ui
However I keep getting the error "couldn't find file 'material-ui". How can I use the material-ui component library in my Rails app with the react-rails gem?
Ok so here is what I have working so far...
to the gemfile I have added:
gem 'react-rails'
gem "browserify-rails"
This gives us our react library, helpers and jsx compilation as well as the ability to use the require() sytax to require modules in our JS. browserify-rails also allows us to require npm modules in your Rails assets via a package.json file.
We can add the material-ui library to our app via this package.json file...
"dependencies" : {
"browserify": "~> 10.2.4",
"browserify-incremental": "^3.0.1",
"material-ui": "0.13.1"
},
The material ui library uses the require syntax to join all the different jsx component files together in the right order so this is why we need to use browserify-rails.
Next to keep our react code together I made a new directory in asset/javascripts called /react...
react
L /components
L react.js
L react-libraries.js
L theme.js
Now as part of 'material-ui' dependencies we have the react library. This means at the moment we have two copies of the library. One from the 'react-rails' gem and one from the 'material-ui' library dependencies from 'browserify-rails'. Lets use the one from 'material-ui' dependencies and leave the one from 'react-rails'.
in react.js:
//= require ./react-libraries
//= require react_ujs
//= require_tree ./components
Then in react-libraries.js
//React Library
React = require('react');
//Material Design Library
MaterialUi = require('material-ui/lib');
injectTapEventPlugin = require('react-tap-event-plugin'); injectTapEventPlugin();
//Material Design Library Custom Theme
MyRawTheme = require('./theme');
ThemeManager = require('material-ui/lib/styles/theme-manager');
Then we want to include all of this in the asset pipeline with...
//= require react/react
in application.js.
Now you can write your components in jsx files in /react/components/
You may also want to namespace your components with...
//Custom Components Namespace
Components = {};
in react-libraries.js
You can customise your theme in theme.js like this...
Colors = require('material-ui/lib/styles/colors');
ColorManipulator = require('material-ui/lib/utils/color-manipulator');
Spacing = require('material-ui/lib/styles/spacing');
module.exports = {
spacing: Spacing,
fontFamily: 'Roboto, sans-serif',
palette: {
primary1Color: Colors.grey300,
primary2Color: Colors.grey300,
primary3Color: Colors.lightBlack,
accent1Color: '#01A9F4',
accent2Color: Colors.grey100,
accent3Color: Colors.grey500,
textColor: Colors.darkBlack,
alternateTextColor: Colors.white,
canvasColor: Colors.white,
borderColor: Colors.grey300,
disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3)
}
};
Hope that helps :)

Resources