Using Browserify with Reactjs - parsing

I am just getting started on a new project which I would like to write in ReactJS. I am trying to use Broserify to bundle everything so that I can have it in multiple js files.
However, when I try to bundle my react file (browserify main.js > bundle.js), I get this error:
"Error: Parsing file /Users/Kathleen/Documents/Referral_Site/main.js: Unexpected token (3:4)"
main.js looks like this:
var Lander = require('./lander');
React.render(
<Lander />,
document.getElementById('content')
);
What's breaking the parser? Thanks in advance!
EDIT: also, I included react in the surrounding html like this:
<script src="http://fb.me/react-0.12.2.js"></script>
is there some way that I need to include it in main.js as well?

You must compile JSX to plain JS first, there is plugin for browserify.
https://www.npmjs.com/package/reactify

Related

openpgp.initWorker is not a function

Please help...I am trying to get openPGP.js working in an existing ASP.Net MVC Web Application.
I first started by adding the following html script tags:
<script src="#Url.Content("~/Scripts/openpgp.min.js")"></script>
<script src="#Url.Content("~/Scripts/openpgp.worker.min.js")"></script>
and I got this error on loading my page:
ReferenceError: importScripts is not defined
So I did some research and added RequireJS to my page, like so:
<script data-main='#Url.Content("~/Scripts/openpgp.min.js")' src="#Url.Content("~/Scripts/require.js")"></script>
Then in the event handler in which I intend to run my decryption logic, I have the following code:
async function decryptBBRecording(commId) {
var openpgp = require(['openpgp']);
await openpgp.initWorker({ path: 'openpgp.worker.js' }) // set the relative web worker path
...
...
...
}
and it is on that "await" line that I am getting
TypeError: openpgp.initWorker is not a function
I'm thinking this is because I have not loaded the openpgp.worker.min.js file. But when I do so via script tag, I get the following errors:
ReferenceError: importScripts is not defined
and when I do so via require(["#Url.Content("~/Scripts/openpgp.worker.min.js")"]); I get this:
Error: Script error for "openpgp"
ReferenceError: importScripts is not defined
Please can you provide me with guidance on how to get this working?
Answer provided here.
You don't have to include openpgp.worker.min.js on the page directly. You also shouldn't need require.js and the call to require. Just include openpgp.min.js on the page, it will globally define openpgp, and then call openpgp.initWorker as you are doing.

How to access custom javascript functions via browser-console in Rails 6

For the sake of debugging the javascript-part of a Rails 6 (version 6.0.0.rc1) web application I want to use my custom javascript functions also in the Chrome console (aka. Inspect).
Back when I used just static HTML files to build a website (as opposed to using a web-framework like Rails as of right now) you would simply embed the JS file in the DOM like this
<!-- custom JS -->
<script src="js/custom.js"></script>
and could instantly access and execute all custom functions that were placed in this file.
Background:
The JS file is placed at the correct rails 6 specific directory as provided in this article: How to require custom JS files in Rails 6
Note:
The rails 6 application also uses the JS file already, since the browser shows the console log message.
Here is the full content of the JS file:
// app/javascript/packs/custom.js
console.log("loaded custom.js successfully")
function sayHello () {
console.log("Hello good Sir or Madam!")
}
Expectation: I am expecting to open the browser's (Chrome) console and be able to use the sayHello() function in the console.
However, when I do so, I get an error message in the console stating:
Uncaught ReferenceError: sayHello is not defined
Try something like
sayHello = ()=>{
console.log("Hello good Sir or Madam!");
}
then you can evoke in console:
>sayHello();

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.NET, Webpack - 'ReactDOM' is undefined (client side)

Following the tutorial here, I have managed to get webpack doing my bundling for me, and it is working for pre-rendering on the server side, e.g.:
#Html.React("Components.myComponent",
New With {
.initialData = Nothing
})
#Html.ReactInitJavaScript()
This is correctly displaying my component in the browser, but as soon as the client takes over I get the error 'ReactDOM' is undefined
I have installed the react-dom using npm install react-dom --save-dev
I have tried to require the ReactDOM, first in the .jsx file containing my component, then in the client.js file that webpack is building from:
//myComponent.jsx
var React = require('react');
var ReactDOM = require('react-dom');
or
//client.js
var ReactDOM = require('react-dom');
var Components = require('expose?Components!./src');
But I am still getting the same error.
If I add the react and react-dom scripts directly above my webpack compiled client javascript, then the problem goes away:
//index.html
<script src="https://www.facebook.com/react-0.14.0.min.js"></script>
<script src="https://www.facebook.com//react-dom-0.14.0.min.js"></script>
<script src="~/Scripts/webpack/build/client.bundle.js"></script>
So how can I get webpack to properly include these scripts in the client bundle?
EDIT
I did have the following externals in my webpack.config.js, but removing them doesn't seem to make any difference.
externals: {
// Use external version of React (from CDN for client-side, or
// bundled with ReactJS.NET for server-side)
react: 'React'
}
I guess, externals are there so you can use CDN based scripts, so maybe I am overthinking this one and should just leave the CDN based react scripts in my view?
You should expose react-dom globally in your client.js, so it will be available in browser in ReactDOM variable to render client-side:
require("expose?ReactDOM!react-dom");

jasmine not loading my custom js file

I am unable to get jasmine to load my custom javascript file, even though it works perfectly in the browser. I've reduced the javascript to the minimum to avoid any possibility of errors and I still get a failing test on the simplest thing.
Custom ARB.js file:
$(document).ready(function() {
alert('typeof ARB: ' + typeof ARB);
});
ARB = {};
ARB.VERSION = "V1.01.00 2012-08-24";
jasmine configuration file snippet (I'm on Rails 3.0.9):
src_files:
- "public/javascripts/**/*.js"
- "public/javascripts/ARB.js"
This test:
it('should define the custom javascript functions', function() {
expect(typeof ARB).toEqual('object');
});
fails with:
Expected 'undefined' to equal 'object'.
jQuery gets loaded and so does my application.js file. When running jasmine, I get no alert message, but I do when I run my app.
What am I missing?
UPDATE: If I remove the $(document).ready function, jasmine passes all the tests - what's that all about?
shioyama gave me the pointer that I needed to figure this out: my custom ARB.js file was getting loaded before the jquery files so it didn't have access to the $(document).ready function. What I had to do was explicitly spell out the order in which my javascript files were to be loaded. Here's what I put in my jasmine config file at /spec/javascripts/support/jasmine.yml:
src_files:
- "public/javascripts/**/jquery.js"
- "public/javascripts/**/jq*.js"
- "public/javascripts/**/application.js"
- "app/assets/javascripts/**/*.js"
- "public/javascripts/ARB.js"
I first force the main jquery.js file to load, then all the other jquery files, then application.js, then any other javascript files that are located in the assets directory, and finally my custom javascript file.
This works for me because I'm still on Rails 3.0.9 and starting the migration to 3.1+ and the asset pipeline.

Resources