Is it possible to export React single page website as HTML? - html

I have a single page web application using React and materialize-css and I would like to export it as static HTML and CSS so that it is possible to easily edit HTML for the purpose of prototyping. Is it possible to export at least a snapshot of current state?
I tried "save page" in Firefox and Chrome, but it does not provide good results.

Follow the following steps :-
1. In brouser, got to the developer tools,
2. select Inspector(firefox)/Elements(chrome),
3. then select the tag HTML, right click on it,
4. then click Edit as HTML.
Now you can copy all the code and save it. While the color and shape of the document remains, you will miss the pictures.
Good luck ! :)

Probably not ideal, but you can store the entire page as a variable and download it. Run this in your browser console after the page has loaded:
var pageHTML = document.documentElement.outerHTML;
var tempEl = document.createElement('a');
tempEl.href = 'data:attachment/text,' + encodeURI(pageHTML);
tempEl.target = '_blank';
tempEl.download = 'thispage.html';
tempEl.click();

The ReactDOMServer module contains a function for rendering a React application to static HTML - it's designed for use on the server, but I don't think there's anything to stop you using it in the browser (don't do this in production though!)
import ReactDOMServer from "react-dom/server";
import App from "./yourComponent";
document.body.innerHTML = ReactDOMServer.renderToStaticMarkup(App);

var pageHTML = window.document.getElementById('divToPDF').innerHTML;
let data = new Blob([pageHTML], {type: 'data:attachment/text,'});
let csvURL = window.URL.createObjectURL(data);
let tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'Graph.html');
tempLink.click();

You can build your code and host it on github.io. The following tutorial will help you achieve that. You can then use the generated code in the gh-pages branch as your exported HTML

This was the first thread I found on SW.. so I think it would be appropriate to copy my own answer from another thread: https://stackoverflow.com/a/72422258/1215913
async function saveToFile() {
const handle = await showSaveFilePicker({
suggestedName: 'index.html',
types: [{
description: 'HTML',
accept: {'text/html': ['.html']},
}]
});
const writable = await handle.createWritable();
await writable.write(document.body.parentNode.innerHTML);
writable.close();
}; saveToFile();
for more info check the source answer

I had done this before but was stuck and couldn't seem to find the documentation anywhere. My scenario was I had a react js SPA and needed to create a static build to run without a server (through an organisations SharePoint using a static doc repository).
It is pretty simple in the end, run
npm run build
in your project directory and it will create the static build in a 'build' folder ready for you to dump wherever needed.
Reference: https://create-react-app.dev/docs/production-build/

Related

How to link an html form to a batch file?

I have this batch file, which is supposed to run the npm package Nativefier:
SET /P _inputname= Please enter a URL:
nativefier %_inputname%
I would like to run this from an electron app's index.html. I have previously tried using an html form and using the following javascript:
$("form").submit(function(){
var WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run ("Experiment.bat");
});
However, this has not seemed to work. Does anyone have a better solution? Any help would be greatly appreciated!
(I am doing this with the intent of building a desktop application, it is not for a webpage)
The ActiveXObject API you're using is only available in old versions of Internet Explorer, and not Chromium (which is the browser engine behind Electron).
In general, in order to run a native executable from Electron, you want to use Node.js child_process module. It should look something like this. Make sure that webPreferences.nodeIntegration is true in your BrowserWindow options so that you can use Node APIs in your renderer process.
const { spawn } = require("child_process");
$("form").submit(() => {
const process = spawn("path/to/executable.bat");
});
Note that you don't necessarily need a .bat file at all.
If you have nativefier as a dependency, you could grab the executable from your node_modules folder and spawn that directly. For instance (assuming that your form submission contains the URL required for Nativefier to run:
const { spawn } = require("child_process");
$("form").submit((myURL) => {
const process = spawn(`/node_modules/path/to/nativefier/binary ${myURL}`);
});

Why does Chrome DevTools show multiple garbled versions of my source code for my Vue application?

I have a Vue application and I'm trying to debug it in Chrome DevTools. The problem is when I try to find the file I want to debug, I get a list of files with the same name plus some weird hash tacked onto the end:
When I open any one file, I get some garbled minified code:
Sometimes I can find the file I want (with the original source code) but sometimes not.
What are these weird files and how can I find the file I want (with the original source code). Is there a way of getting the DevTools to list only the original source code files?
Thanks.
What tool in dev tools are you using to get that list? Seems like a list of cached files, so it's showing all the old versions of your code.
If you go to the network tab and reload the page. You should see a list of all the resources downloaded by the browser. Choose the js filter and you should see your vue js bundle (made by webpack) somewhere in that list.
To allow chrome to display the source correctly you need to generate the Source Maps in development deployments.
I am not sure what tool you are using to build and bundle, but it is likely that you might have support for this already.
Chrome Details:
https://developer.chrome.com/docs/devtools/javascript/source-maps/
OMG - debugging my debugging environment. It's SO maddening.
I'm working with Vue v2, and I'm using vuetify in my app. Here is a complete vue.config.js configuration that solved this problem for me.
// vue.config.js file
const path = require('path')
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: [
'vuetify'
],
configureWebpack: config => {
if (process.env.NODE_ENV === 'development') {
// See available sourcemaps:
// https://webpack.js.org/configuration/devtool/#devtool
config.devtool = 'eval-source-map'
// console.log(`NOTICE: vue.config.js directive: ${config.devtool}`)
config.output.devtoolModuleFilenameTemplate = info => {
let resPath = path.normalize(info.resourcePath)
let isVue = resPath.match(/\.vue$/)
let isGenerated = info.allLoaders
let generated = `webpack-generated:///${resPath}?${info.hash}`
let vuesource = `vue-source:///${resPath}`
return isVue && isGenerated ? generated : vuesource
}
config.output.devtoolFallbackModuleFilenameTemplate =
'webpack:///[resource-path]?[hash]'
}
},
})
I found a work around for this. While you can not see the source code of your file, just change the code (add console or sth.) of the file you want to see while Vue is hot reloading your changes. It occurs to me that the source code is then reachable when you check the developer console.
There is a surprising number of developers I meet on projects that have no idea there are official browser extensions for debugging Vue, Router, VueX etc.
Stumbling across this question prompted me to post this life saving link for those that land here and have missed the existence of this essential tool:
https://devtools.vuejs.org/guide/installation.html

How to get "Coverage" data out from the Chrome Dev Tools

I am using the Coverage tab at my Chrome Dev Tools and I have a really big file and after playing a lot with Coverage it's clear enough that only 15% enough of my CSS code is being used (I simulated button presses, hover menus...).
The problem is getting hat 15% of code OUT of the Coverage tab. I cant believe the Devs behind this really nice feature didnt think an easy way for the end user copy only the green part of the code. Check image attached.
Do you have any idea how I could do that? I read something about using Puppeteers but it requires lots of preparation. On latest Canary version it looks like I can export a JSON but it would require some time to code a parser to that JSON in order to extract only the needed part.
Thanks to an article by Phillip Kriegel (https://www.philkrie.me/2018/07/04/extracting-coverage.html) I managed to setup Puppeteer to extract the coverage CSS from a URL and output that CSS into a file.
Here's how to do it:
Step 1: Install node.js globally
Step 2: Create a folder on your desktop
Step 3: Inside the folder install the Node Package Manager (NPM) and the Puppeteer node module
Step 4: Create a JavaScript file inside the folder, name it coverage.js
Step 5: Put this code inside that js file:
const puppeteer = require('puppeteer');
// Include to be able to export files w/ node
const fs = require('fs');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Begin collecting CSS coverage data
await Promise.all([
page.coverage.startCSSCoverage()
]);
// Visit desired page
await page.goto('https://www.google.com');
//Stop collection and retrieve the coverage iterator
const cssCoverage = await Promise.all([
page.coverage.stopCSSCoverage(),
]);
//Investigate CSS Coverage and Extract Used CSS
const css_coverage = [...cssCoverage];
let css_used_bytes = 0;
let css_total_bytes = 0;
let covered_css = "";
for (const entry of css_coverage[0]) {
css_total_bytes += entry.text.length;
console.log(`Total Bytes for ${entry.url}: ${entry.text.length}`);
for (const range of entry.ranges){
css_used_bytes += range.end - range.start - 1;
covered_css += entry.text.slice(range.start, range.end) + "\n";
}
}
console.log(`Total Bytes of CSS: ${css_total_bytes}`);
console.log(`Used Bytes of CSS: ${css_used_bytes}`);
fs.writeFile("./exported_css.css", covered_css, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
await browser.close();
})();
Step 6: BE SURE TO REPLACE the URL at this point in the code await page.goto('https://www.google.com'); with your desired URL
Step 7: In the command line tool (Git Bash) type node coverage.js
A file called exported_css.css will be created, it will contain all your coverage CSS for the URL you set in the code.
CAVEAT: This will extract the coverage CSS from ALL the CSS assets that are loaded from the URL you set. You will then have to further optimize that CSS (not covered in this example).
Open Chrome Tab --> Inspect Element (F12) --> Press Escape button
I'm in the process of creating a PHP script that parses the Coverage JSON exported file, and outputs the extracted used CSS/JS only. Unfortunately I have come across a snag, at some point the JSON parser loses the correct character number, and I end up with broken or incorrect CSS/JS syntax. It's only off by a few characters, but the amount of characters that it is off by is variable so it's almost impossible to predict it during parsing.
I'm not positive, but I think the issue results from PHP running on the server, and the server may read the characters in the original CSS file differently than a browser would. I'm going to attempt to write a Coverage JSON parser in JavaScript. When I do I'll be sure to post the code here for all to use.
Sorry I couldn't be of more help, I just wanted to warn away people from using PHP to do this as it seems to not read character numbers correctly in large CSS files.

Accessing filesystem in Angular 5, using electron

I'm building an simple stand-alone angular application in which u can submit information.
This information needs to be saved in a local JSON file that's in the asset folder. I know Angular runs in a web browser that's why I use electron to build it. The problem is that i can't figure out a way to edit the JSON files in angular 5 using electron (local).
I have tried the solutions mentioned in this post, But they didn't work for me, any other solutions?
After having this problem for quite some time i finally figured out how to solve it:
you need to put this in script tags in your index.html
var remote = require('electron').remote
var fs = remote.require('fs');
and in every component you want to use it you need to declare it globally
declare var fs: any;
then you can use it!
was quite a struggel to figure it out...
Because it's just JSON data, might I suggest using localStorage instead? Then, you can do something like:
...// Code that creates the JSON object
var theJSONdata = jsonObj.stringify(); // conver the object to a string
window.localStorage.setItem('mysavedJSON', theJSONdata)
;
Later, when you need to load the JSON to edit it or read it, just use:
jsonObj = JSON.parse(window.localStorage.getItem('mysavedJSON');

Polymer - url rooting after deployment to subdirectory

Ive created a basic Polymer app from the starter kit (via Yeoman). I've today deployed it to the 'sandbox' on my domain and am getting a strange routing issue. The app is essentially a feed reader.
View app here
When I first visit the app I'm given a blank page whereas locally I'm taken straight to the feed. When clicking on 'News Feed' I'm then taken to the feed as expected.
I've added a route for the path of the domain structure as below but this did not fix it.
You can view the full code of the project here.
routing.html
page('/', function () {
app.route = 'home';
});
page('http://purelywebdesign.co.uk/sandbox/f1feedreader/', function () {
app.route = 'home';
});
I've also tried:
page('/sandbox/f1feedreader/', function () {
app.route = 'home';
});
Any help much appreciated.
Page.js allows you to configure the base path:
page.base('/sandbox/f1feedreader/');
or just use window.location if you don't want to tie is to that specific deployment.
page.base(window.location.pathname);
This is an issue with the way the router page.js works. I assume you were testing with gulp serve (which creates a server and sets the web app base url of "/" to be localhost:3000/). The way you're currently setting your page.js routes is that it's looking exactly after the domain name and not at the "root" of the web directory.
In your case page.js is looking at everything after http://purelywebdesign.co.uk/ (meaning all your routes include should start from sandbox/f1feedreader instead of just /f1feedreader).
The documentation for page.js https://visionmedia.github.io/page.js/ says that it uses regular expressions so you could also update the strings.