I'm trying to embed a small react app into a squarespace site.
Here's the page: https://www.birdiebreak.com/referral-profile?referralCode=WHUOS
I can get the react app to load just fine but various parts of the site disappear! Specifically the header and any images on the page.
I've tried using the Code widget as well as the Embed widget with both have the same result.
I did try a basic Create React App site to see if the minimal code I built was the problem but got the same issues.
Has anyone managed to do this successfully?
I don't know why exactly, but if I add a script tag into the body referencing my react app <script src="path-to-react/main.buildcode.js" /> parts of the squarespace site just stop loading.
However if instead I add a script loader things work just fine.
<script type="text/javascript">
(function (g, r, head, script) {
head = r.getElementsByTagName("head")[0];
script = r.createElement("script");
script.async = 1;
script.src = "https://birdie-break-develop.azurewebsites.net/static/js/main.d2ee648d.js";
head.appendChild(script);
})(window, document);
</script>
I've had success using a modified version of the Add React to a Website guide in the React docs. Assuming you have access to the source code for your React app, the following steps should work:
Add a Code Block with a single empty div containing a unique ID ('custom-react-root', or whatever you'd like). This is where your React app will render.
Configure your index.js to use this block as the root:
function run() {
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('custom-react-root')
);
}
Run the build command for your build tool to create the minified JS files. (e.g. yarn build)
Wrap the minified JS files in <script> tags, and the CSS file in <style> tags. I wrote a bash script to do this, which includes the following lines:
(
echo "<script>"
cat build/static/js/2.*.chunk.js
echo "</script>"
echo "<script>"
cat build/static/js/main.*.chunk.js
echo "</script>"
echo "<script>"
cat build/static/js/runtime-main.*.js
echo "</script>"
echo "<style>"
cat build/static/css/*.chunk.css
echo "</style>"
) > build/injectable.html
Paste these tags into the Page Header, as described in the SquareSpace docs.
Related
I am embedding a react project inside my django app. I am serving the index.html file created by npm run build from django as opposed to just using django as a third party api. I like this approach as it leverages django user authentication/ csrf tokens/ etc.
After npm run build I am extracting the head and the scripts on index.html and putting them in my base.html of django, this way, the react scripts will be available wherever I need them and I can use my django templates for my navbar, footer etc.
The problem I am having is I have to copy and paste the headers and scripts on every build, so my question is if there is a way to make npm run build build the files with the same name every time, or perhaps another solution, so when I rebuild the react project I don't have to recopy and paste to base.html?
Here is a code snippet sample
base.html
<html>
<head>
<!-- Copy and pasted header files from react build-->
</head>
<body>
<navbar></navbar>
{% block content %}
{% endblock %}
<script> //copy and pasted scripts from react build - different script names on every build </script>
</body>
</html>
And then a file served by django
homepage.html
{% extend 'base.html' %}
<div class="other-django-stuff"></div>
{% block content %}
<div id="root"></div> // where my react project is anchored
{% endblock %}
Well, so what is needed in this case is a post build script that allows you to edit the file called base.html to have the right names and scripts produced by the build. I will describe here some conceptual steps on how to achieve this result.
Step n. 1: Change the package.json file to allow the execution of a script after the build
In this case I am using a JavaScript script file that will be run using nodejs, but you can use also other languages or shell scripts
"scripts": {
...
"build": "react-scripts build && node ./postbuild.js",
...
},
Note that, since the && operator is used, the postbuild.js file will executed only if the build will have success.
Step n. 2: Create the post build script that will write your base.html file
With the script you will be able to write the base.html file dynamically.
Note:
Since you can create the script in different languages, the script itself it is not included in the answer.
Thanks to Emanuele's guidance Here is the following solution using python. This assumes the react static build folder is added to STATIC_DIRS in settings.py:
base.html
<html>
<head>
{% include 'react_head.html' %}
</head>
<body>
<navbar></navbar>
{% block content %}
{% endblock %}
{% include 'react_scripts.html' %}
<script src='django-scripts.js'></script>
</body>
</html>
build_base.py
from bs4 import BeautifulSoup
index = open( "build/index.html" )
soup = BeautifulSoup( index, features="html.parser" )
links = soup.findAll( "link" )
scripts = soup.findAll( "script" )
with open( "./../templates/react_head.html", "w" ) as html:
html.write( r"{% load static %}" + "\n" )
for link in links:
url = link["href"]
if "favicon" in url: continue
fname = "/".join( url.split("/static/")[1:] )
link["href"] = '{% static ' + f"'{fname}' " + r"%}"
html.write( link.prettify() )
with open( "./../templates/react_scripts.html", "w" ) as html:
html.write( r"{% load static %}" + "\n" )
for script in scripts:
if 'src' in script:
url = script["src"]
fname = "/".join( url.split("/static/")[1:] )
script["src"] = '{% static ' + f"'{fname}' " + r"%}"
html.write( script.prettify() )
package.json
"scripts": {
...
"build": "react-scripts build && python ./build_base.py",
...
},
That error doesn't show up when I open the html page manually but it does when I try to connect it to a different .js file using
import main from './Components/Shopping/function';
and
<Route path="/Shopping">
<main />
</Route>
before running it with nodemon app and npm start.
Also, when I enclose all the code in function.js in a function using
var main = () => {
//code
}
export default main;
for the routing, the code in function.js doesn't work when I manually open the HTML file that uses it.
Edit: Apparently all it needed was npm install underscore in the cmd in the directory with function.js, and const _ = require("underscore"); in function.js. But even though there are no errors, it won't load the webpage. It's just blank, apart from a navigation bar (But the URL does change to (url)/Shopping). And the HTML page opened manually still can't use the code from function.js.
I am testing Jimp.js for image manipulation (using React with react-scripts, npm: 6.14.4, node: v12.16.3)
Everything is going well except writing text on a loaded image
import Jimp from 'jimp'
Jimp.read(image)
.then(image => {
console.log('image loaded', image)
Jimp.loadFont(Jimp.FONT_SANS_32_WHITE).then(font => {
console.log('font loaded', font)
image.print(font, 10, 10, 'Hello world that wraps!', 12)
// write image
})
})
This throws an error "error parsing font malformed file -- no element" in browser.js of load-bmfont module line 71 and dont execute the log 'font loaded'.
Googling not help i found only 2,3 items about this, associate with using custom fonts - but i use standard font from Jimp. (Using BMFont files instead of Jimp standard fonts doesnt help)
My first thought was the error ocured in a React App in the browser, so i write a Jest test to see if its work without browser context but it fail just like that.
Got any ideas?
Solved...
I'm using the React App within a Java Web Framework in a JSP File.
Jimp.loadFont(Jimp.FONT_SANS_32_WHITE)
search the font in a path that doesn`t exist for the webapp.
Moving the font files to a reachable path with context root
Jimp.loadFont(`${CONTEXT_ROOT}/foo/bar/font.font`) works.
My question is similar to this existing question i.e. A Web project is already using - Spring MVC + Angular1.x + JSP + JavaScript etc.
Page layout is already designed with tiles technology and I have to develop a sample page - only body part i.e. I have to keep doing layout with tiles and have to reuse - header , footer , left navigation etc .
So I set up a separate Angular2 project , build it and included final JS files in layout JSP of tiles.
In my new body jsp, when I use angular2 root component , my jSP is displaying perfectly but all other pages of application are showing this below error,
core.es5.js:1020 ERROR Error: The selector "app-root" did not match any elements
at DefaultDomRenderer2.selectRootElement (platform-browser.es5.js:2791)
at createElement (core.es5.js:9172)
at createViewNodes (core.es5.js:12146)
at createRootView (core.es5.js:12075)
at Object.createProdRootView [as createRootView] (core.es5.js:12760)
at ComponentFactory_.create (core.es5.js:9858)
at ComponentFactoryBoundToModule.create (core.es5.js:3333)
at ApplicationRef_.bootstrap (core.es5.js:4763)
at core.es5.js:4546
at Array.forEach (<anonymous>)
defaultErrorLogger # core.es5.js:1020
zone.js:654 Unhandled Promise rejection: The selector "app-root" did not match any elements ; Zone: <root> ; Task: Promise.then ; Value: Error: The selector "app-root" did not match any elements
at DefaultDomRenderer2.selectRootElement (platform-browser.es5.js:2791)
at createElement (core.es5.js:9172)
at createViewNodes (core.es5.js:12146)
at createRootView (core.es5.js:12075)
at Object.createProdRootView [as createRootView] (core.es5.js:12760)
at ComponentFactory_.create (core.es5.js:9858)
at ComponentFactoryBoundToModule.create (core.es5.js:3333)
at ApplicationRef_.bootstrap (core.es5.js:4763)
at core.es5.js:4546
at Array.forEach (<anonymous>) Error: The selector "app-root" did not match any elements
at DefaultDomRenderer2.selectRootElement
This above error is on console and those other JSP pages keep working correctly and this background error affects them in no way.
This error doesn't come on JSP page where I call root component i.e. my new jsp body page.
I have included angualr2 JS files outside outside body tag at bottom.
Any suggestions to remove this error from console and if this set up looks OK?
We will set up an automated process to build and copy files from Angualr2 UI project to Spring MVC project and only those final JS files will be deployed with app.
Its an Spring MVC controller which loads the page for the first time - a JSP .
With inputs from JB Nizet from comments , I am able to resolve issue by removing angular js inclusions from common application layout JSP and putting it in body jsp file as shown below.
<app-root>Loading...</app-root>
<!-- For Angular 2 -->
<script type="text/javascript" src="inline.bundle.js" ></script>
<script type="text/javascript" src="polyfills.bundle.js" ></script>
<script type="text/javascript" src="styles.bundle.js" ></script>
<script type="text/javascript" src="vendor.bundle.js" ></script>
<script type="text/javascript" src="main.bundle.js" > </script>
I am building application with - ng build --env=prod --output-hashing none
I if I do JS inclusions before calling root component, error occurs.
I want to require two bundle files from webpack in an app.js that also gets bundled. My folder looks like this:
MyApp
|-app
| -app.js <-this gets bundled
|-hero
| -hero.module <- this gets also bundled
| -some other stuff that will be bundled in hero.bundle.js
|-crisis
| -crisis.module <- gets bundled
| -more stuff that gets bundled in crisis.bundle.js
-
So far so good.
I want to require hero.bundle.js and crisis.bundle.js in the app.js, because I am lazy loading / routing with my COmponent Router in app.js.
But I get constantly the Error, that the modules couldn't be found.
Example Syntax of one of the requires:
path: '/heroes/...',
name: 'Heroes',
loader: function () {
// lazy load Heroes
return $ocLazyLoad.load([require('./dist/heroes.bundle.js')])
.then(function () {
return 'heroes';
});
}
Do I do something wrong?
Thanks in advance :)
I got the solution:
Webpack didn't find my files. The path searched
C:/someFolders/heroApp/app/dist/heroes.bundle.js
altough it was
C:/someFolders/heroApp/dist/heroes.bundles.js
setting two dots was the solution:
require('../dist/heroes.bundle.js')