How to use RequireJs to load React then ReactDom Sequentially? - javascript

ReactDOM depends on React to be loaded before it is loaded, in a sequential manner.
I have to load scripts with requirejs, as I cannot change the synchronous loading of js.
I have tried creating a test app but I keep getting the following error: Error: Script error for "react", needed by: helper/react-dom.min
after hello is printed
What I have tried...
Index.html
<!DOCTYPE html>
<html>
<head>
<title>My Sample Project</title>
<!-- data-main attribute tells require.js to load
scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>My Sample Project</h1>
</body>
</html>
main.js
require(['helper/react-loader'], function(){
// do something with the loaded modules
console.log('hello);
});
react-loader.js
require(['helper/react.min','helper/react-dom.min'], function(){
// do something with the loaded modules
console.log('react loaded');
});

ReactDOM uses define(['react'], f) to define module (see), so you have to define React module's name equals to react, which means you config requirejs like below:
require.config({
paths: {
'react': 'helper/react.min',
}
});

Related

Can I run index.html with React without npm start and npx create-react-app?

I am self-learning react and I am just confused about a lot of things.
I thought that if I add React to my index.html via a script like the below:-
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bill Details</title>
</head>
<body>
<div id="billTable"></div>
<script src="BillTable.js" type="text/javascript"></script> ------------- Problem Line 1
</script>
</body>
</html>
and this is my js file where I am trying to return react component
//BillTable.js
import React from "react";
import ReactDOM from "react-dom";
function BillTable() {
return <h1>HELLO TABLE</h1>;
}
ReactDOM.render(<BillTable/>, document.getElementById("billTable"));
when I try to open index.html directly in firefox or through express server I get the below error in console:-
Uncaught SyntaxError: import declarations may only appear at top level of a module.
I then got rid of this error by changing the script type in problem line 1 in index.html to
<script src="BillTable.js" type="text/babel"></script>
but then also my webpage is completely blank and even console is not showing any errors.
Please suggest how to solve this issue. I am right now trying to learn React with functional approach only, so if any changes are required to be done on the react side, please make them in the functional approach.
I don't think you have included the correct packages to handle React components and JSX yet. These packages react, react-dom, etc. are usually in a package.json and are required to tell the browser what tools will be used to run the code. These packages handle the "script" or components you create and places the elements constructed in your components to the DOM. You can solve this by loading react with additional script tags before your component's script tag. This will let the browser know how and what to use to run your react component. Also, in your function, it does not know that it is a React Component. Check out an explanation for why you would have to use React.createElement I have attached an example of using only an index.html page here:
example of using an index.html page
Your Component file:
"use strict";
function BillTable() {
return React.createElement("h1", "", "HELLO TABLE");
}
const domContainer = document.querySelector("#billTable");
const root = ReactDOM.createRoot(domContainer);
root.render(React.createElement(BillTable));
and your index.html:
<body>
<div id="billTable"></div>
<!-- Load your React packages -->
<script
src="https://unpkg.com/react#18/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"
crossorigin
></script>
<!-- Load your React component. -->
<script src="BillTable.js"></script>
</body>

JavaScript Imports

I am trying to call the function popup from within index.html. When I view this code below in the browser I get this error ReferenceError: popup is not defined. The reason why I am trying to do this is to better organize my code when I have many functions, I thought it might be easier to import them all into one file and then import that file into my index.html file. I don't know if this is best practice or not, but I thought it would help.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.scss">
<script type="module" src="main.js"></script>
</head>
<body>
<script>popup("testing")</script>
</body>
</html>
main.js
import { popup } from './main/popup.js';
popup.js
export function popup(x) {
alert(x);
}
Your main.js runs in a module, not on the top level. If you want to be able to reference it outside, from a non-module script, either explicitly put it onto the window to make it global:
import { popup } from './main/popup.js';
window.popup = popup;
(though, that kind of defeats the purpose of using modules at all)
Or put the script that calls popup into a module as well (rather than in an inline script):
<body>
<script type="module" src='bodyScript.js'></script>
</body>
// bodyScript.js
import { popup } from './main/popup.js';
popup("testing");

webpack, process env variable in index.html

I have a react app which has an entrypoint of my app.jsx and I am adding segment.io to my build, however I would like to set it's API key as an process.env variable. I am having trouble with how to do this with webpack because my entry point is not the index.html.
I am trying to see if there is a way so I can (on the index.html) do something like this
<script type="text/javascript">
..segment script loading here + (process.env.MY_SEGMENT_KEY)}();
</script>
But I am not sure how to get it so I can process env variables at the index.html level.
In app.jsx I am toggling the code like :
if (process.env.MY_SEGMENT_KEY) {
....
}
and this works fine because I have access to the vars at this point. I would like to also conditionally load the script on the index.html. Anyone know if this is possible? Thanks!
Just load analytics in your JSX file as follow:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
if (process.env.MY_SEGMENT_KEY) {
window.analytics.load(process.env.MY_SEGMENT_KEY);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Your index.html file should look like that:
<!DOCTYPE html>
<html>
<head>
...
<title>My App</title>
<script type="text/javascript">
!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="4.0.0";
}}();
</script>
</head>
<body>
<div id="root">
</div>
</body>
</html>

require js is not loading the modules from the configs

I have the index.html as:
<!DOCTYPE html>
<html>
<head>
<script data-main="scripts/main" src="lib/require.js"></script>
</head>
<body>
<h1>Example 1: basic usage</h1>
</body>
</html>
and the main.js:
requirejs.config({
waitSeconds: 200,
paths: {
"app": "app"
}
});
and the app.js:
define(function () {
alert('Hello World');
});
both main and app are under scripts folder.
When I opened the index.html, and in the console if I give:
require("app")
I get an error like this:
Uncaught Error: Module name "app" has not been loaded yet for context: _. Use require([])
Not sure, where I have made mistake.
You haven't started your app, to do this you should call requirejs(['app/app']).
Here is the basic requirejs example https://github.com/volojs/create-template/tree/master/www

coffeescript: suppress "ReferenceError"

Currently working through this tutorial on using Backbone.js with coffeescript.
Leveraging the following index.html file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CoffeeScript, Meet Backbone.js: Part N</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script type="text/javascript" src="./index.js"></script>
</head>
<body>
<header>
<h1>CoffeeScript, Meet Backbone.js: Part 1</h1>
</header>
</body>
</html>
which loads an index.js file after loading Backbone, jQuery, etc from a cdn. Hoping to work within a script.coffee file that I'd like to have automatically compile into the script.js file loaded by index.html above by running something like coffee script.coffee -c -w.
Trouble is, I'm getting ReferenceErrors when I try to run the above command on the following script.coffee file:
jQuery ->
class ListView extends Backbone.View
el: $ 'body'
initialize: ->
_.bindAll #
#render()
render: ->
$(#el).append '<ul><li>Hello, Backbone!</li></ul>'
list_view = new ListView
For instance:
ReferenceError: jQuery is not defined
...
because, clearly, jQuery is being loaded in the index.html file.
Is there a way to suppress the error reporting from the coffeescript compiler so that it just converts the code without the error?
The options must go before the file, e.g.:
coffee -cw script.coffee
Otherwise, it will try to run script.coffee right then and there as a Node.js script, passing it the options -c and -w. That's not what you want; if you want the CoffeeScript compiler to get the options, it's got to be before the file name.

Categories