GatsbyJS: How do I load a component synchronously at build time, but asynchronously at runtime? - javascript

I have a Gatsby site with a React component called ArticleBody that uses react-markdown to convert an article written in Markdown to a React tree.
As this is a bit of an expensive operation and a somewhat large component — and for SEO reasons — I'd like to pre-render ArticleBody at build time. However, I'd also like to load ArticleBody asynchronously in the client. Since the article body will already be included in the HTML, there's no rush to load and render the Markdown component in the client, so async should be fine.
How would I accomplish this? It's almost as if I want to have two different JS bundles — one bundle that loads ArticleBody synchronously, for the build, and one that loads it asynchronously, for the client. Is this possible in Gatsby?
Thanks!

Instead of React.lazy which is not supported, you can use loadable components. There is a Gatsby plugin to handle SSR correctly gatsby-plugin-loadable-components-ssr
Currently there is an issue with it since Gatsby 3.x, but there is a way to implement it yourself without the extra plugin. See the comment in the issue here. Also add the changes mentioned in the comment below of it.
I haven't tried this specific implementation yet, but it should work with the following steps:
npm install --save-dev #loadable/babel-plugin #loadable/server #loadable/webpack-plugin #loadable/component
gatsby-browser.js
import { loadableReady } from '#loadable/component'
import { hydrate } from 'react-dom'
export const replaceHydrateFunction = () => (element, container, callback) => {
loadableReady(() => {
hydrate(element, container, callback)
})
}
gatsby-node.js
exports.onCreateWebpackConfig = ({ actions, stage }) => {
if (
stage === "build-javascript" ||
stage === "develop" ||
stage === "develop-html"
) {
actions.setWebpackConfig({
plugins: [
new LoadablePlugin({
filename:
stage === "develop"
? `public/loadable-stats.json`
: "loadable-stats.json",
writeToDisk: true
})
]
});
}
};
gatsby-ssr.js
import { ChunkExtractor } from '#loadable/server'
import path from 'path'
const extractor = new ChunkExtractor({
// Read the stats file generated by webpack loadable plugin.
statsFile: path.resolve('./public/loadable-stats.json'),
entrypoints: [],
})
// extractor.collectChunks() will wrap the application in a ChunkExtractorManager
export const wrapRootElement = ({ element }) =>
extractor.collectChunks(element)
export const onRenderBody = ({ setHeadComponents, setPostBodyComponents }) => {
// Set link rel="preload" tags in the head to start the request asap. This will NOT parse the assets fetched
setHeadComponents(extractor.getLinkElements())
// Set script and style tags at the end of the document to parse the assets.
setPostBodyComponents([...extractor.getScriptElements(), ...extractor.getStyleElements()])
// Reset collected chunks after each page is rendered
extractor.chunks = []
}
If you have DEV_SSR enabled, you should not add stage === "develop-html". Otherwise, you are good.
Hope this summary of the issue's comments help to get you started.

Related

Dynamically loaded script is not using dynamically loaded css until I 'prettify' css in devtools source

I am experimenting with mounting an existing Ember app in a React app. I have a React component that loads the vendor/app .css and then the vendor/app .js, with an await between each load. The app shows up in the React component but it doesn't use any of the styles from the dynamically loaded css until I go into devtools/source, find the .css file, and click the 'prettify' widget ("{}"). Then it immediately repaints the screen with the css applied correctly.
I even tried doing a this.forceUpdate after the load.
Any idea what I'm doing wrong? Or a way of triggering the browser to reapply the css from within my component's javascript?
Edit: More details about how things are arranged - see the code I'm using to load the 'emberapp' files below.
The React App, which I'm still learning, does a webpack build when starting (I realize that's probably not descriptive enough but will update when I learn more). It runs a proxy server for the API wrapped around an express server that serves the local app. Might be relevant - the React app components import their css at the component level.
During yarn start, react-app/dist gets destroyed so after the start finishes rebuilding and re-webpacking, I cd into react-app/dist and do a ln /path/to/ember-app/dist/assets emberapp
The ember-app/dist/assets contains
emberapp.js
emberapp.css
vendor.js
vendorapp.css
I also have all of my svg's inlined and loaded through the index.html - they obviously don't load right now and I'm OK with that.
This is really just a temporary setup for end-to-end API testing. I was just really surprised that the css was ignored util I clicked something in devtools, and then was suddenly loaded. I thought it might be a 'known' behavior.
My current goal is to repackage my ember app into an npm package that I can include in the build of the react app and 'import' its app/vendor js/css.
I know this isn't a great solution but we've got a lot of time built into the Ember App and don't have time to fully re-write it in React. When we started the Ember App 'how will we merge this into another app when we are acquired' was not a consideration.
If anyone has any recommendations along embedding Ember, I'd be interested in that too.
const appendScript = scriptToAppend => {
return new Promise(resolve => {
const _wrap = () => {
console.log('_script onload wrap');
resolve();
};
const script = document.createElement('script');
script.setAttribute('src', scriptToAppend);
script.setAttribute('async',true);
script.onload = _wrap;
document.body.appendChild(script);
});
};
const appendCss = cssToAdd => {
return new Promise(resolve => {
const _wrap = () => {
console.log('appendCss onLoad handler');
resolve();
};
const elem = document.createElement('link');
elem.setAttribute('rel', 'stylesheet');
elem.setAttribute('type', 'text/css');
elem.setAttribute('href', cssToAdd);
elem.onload = _wrap;
document.getElementsByTagName('head')[0].appendChild(elem);
});
};
export class MyWrapper extends React.Component {
async componentDidMount() {
await appendCss(`${EMBED_SCRIPT_PATH}${VENDOR_SCRIPT_NAME}.css`);
await appendCss(`${EMBED_SCRIPT_PATH}${SCRIPT_NAME}.css`);
await appendScript(`${EMBED_SCRIPT_PATH}${VENDOR_SCRIPT_NAME}.js`);
await appendScript(`${EMBED_SCRIPT_PATH}${SCRIPT_NAME}.js`);
this.forceUpdate();
}
}

Next js named imports with no SSR

I need to convert this line to next.js dynamic import and also without SSR
import { widget } from "./charting_library/charting_library";
I have tried this one
const widget = dynamic(() => import("./charting_library/charting_library").then((mod) => mod.widget), {
ssr: false
});
This seems not the correct way and also charting_libray.js file is a compiled js file in a previous project.
Is the problem is my importing method or the js file? If this is importing method how do I fix this?
const { widget } = await import("./charting_library/charting_library")
Maybe something along those lines might work? As for the SSR side I am not sure if you would need to execute it within a useEffect.

Webpack not allowing es2020 import from variable in next.js

I'm developing a plugin feature in my next.js react app in which I have to dynamically import components from a bunch of given modules.
component.tsx :
const MyComponent = (props) => {
useEffect(() => {
const pluginNames = ['test-component'];
pluginNames.forEach(async (name) => {
try {
const plugin = await import(name);
} catch(err) {
// I don't want an unvalid plugin to crash my app
console.warn(err);
}
});
}, []);
// returns any html template
}
but when I run my code, I get the following error:
it seem to clearly indicate that the plugin is not found despite it's installed.
From what I understood, it happens because webpack doesn't pack up the dynamically imported plugins in my webpack config. Is there a way to tell webpack to include the specified modules (considering they are fixed since the startup of the app).
Possible solutions:
create a js file importing all modules and tell webpack to inject it into the bundle page
configure webpack so it adds the required modules

How can I pre-render a react app in gulp/node?

How can I programmatically render a react app in gulp and node 12?
I taking over and upgrading an old react (0.12.0) app to latest. This also involved upgrading to ES6. The react code itself is done, but we also need to prerender the application (The app is an interactive documentation and must be crawled by search engines).
Previously, the gulp build process ran browserify on the code and then ran it with vm.runInContext:
// source code for the bundle
const component = path.resolve(SRC_DIR + subDir, relComponent);
vm.runInNewContext(
fs.readFileSync(BUILD_DIR + 'bundle.js') + // ugly
'\nrequire("react").renderToString(' +
'require("react").createElement(require(component)))',
{
global: {
React: React,
Immutable: Immutable,
},
window: {},
component: component,
console: console,
}
);
I am suprised it worked before, but it really did. But now it fails, because the source uses ES6.
I looked for pre-made solutions, but they seem all targeting old react versions, where react-tools was still around.
I packaged the special server-side script below with browserify & babel and then ran it using runInNewContext. It does not fail but also not output any code, it just logs an empty object
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './index';
const content = renderToString(<App />);
I found tons of articles about "server-side rendering", but they all seem to be about rendering with express and use the same lines as the script above. I can't run that code directly in gulp, as it does not play well with ES6 imports, which are only available after node 14 (and are experimental).
I failed to show the gulp-browserify task, which was rendering the app component directly, instead of the server-side entrypoint script above. In case anyone ever needs to do this, here is a working solution.
Using vm.runInNewContext allows us to define a synthetic browser context, which require does not. This is important if you access window anywhere in the app.
src/server.js:
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './index';
const content = renderToString(<App />);
global.output = content;
above script serves as entry point to browserify. Gulp task to compile:
function gulpJS() {
const sourcePath = path.join(SRC_DIR, 'src/server.js');
return browserify(sourcePath, { debug:true })
.transform('babelify', {
presets: [
["#babel/preset-env", { targets: "> 0.25%, not dead" }],
"#babel/preset-react",
],
})
.bundle()
.pipe(source('server_output.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('.'))
.pipe(dest(BUILD_DIR));
}
The generated file can now be used by later tasks, e.g. to insert the rendered content into a HTML file.
const componentContent = fs.readFileSync(path.join(BUILD_DIR, 'server.js'));
const context = {
global: {
React: React,
Immutable: Immutable,
data: {
Immutable
},
},
window: {
addEventListener() { /* fake */ },
removeEventListener() { /* fake */ },
},
console,
};
vm.runInNewContext(componentContent, context);
const result = context.global.output;

Importing single file components VueJS

everyone.
I have a trivial doubt on making vue components.
I don't want to use browserify or webpack , cause I am working in django and it has most of it's templates in static files , although I read this , which does describe how to take in account both ( but that's for some other day ).
Problem :
I am making a single file component which I have to import and use, using my router but I can't, as the import just doesn't happen.
My Hello.vue
<template>
Some HTML code here.
</template>
<script>
module.exports = {
data() {
return {
coin : []
}
},
beforeRouteEnter (to, from, next) {
axios.get('my-django-rest-api-url')
.then(response => {
next(vm => {
vm.data = response.data
})
})
}
}
</script>
I have it in the index.html file itself , no other .js file,
<script>
import Hello from '#/components/Hello.vue'
Vue.use(VueRouter);
const dashboard = {template:'<p>This is the base template</p>'};
const profile = {
template: '#profile_template',
data () {
return {
profile_details: []
}
},
beforeRouteEnter (to, from, next) {
axios.get('my-api-url')
.then(response => {
next(vm => {
vm.profile_details = response.data
})
})
}
}
const router = new VueRouter({
routes: [
{ path: '/', component: dashboard },
{ path: '/profile', component: profile },
{ path: '/hello', component: Hello }
]
});
new Vue({
router : router,
}).$mount('#app');
</script>
What all I've tried :
1.<script src="../components/Hello.js" type="module"></script> and removing the import statement as suggested here
Replacing my Hello.js's code with this : export const Hello = { ...
Making a Hello.js file and importing it like this import Hello from '../components/Hello.js';
Error :
**Mozilla ( Quantum 57.0.4 64 bit ) ** : SyntaxError: import declarations may only appear at top level of a module
**Chrome ( 63.0.3239.108 (Official Build) (64-bit) ) ** :Uncaught SyntaxError: Unexpected identifier
P.S. : I have tried these in various combinations
Not a Vue.js guru, but here are a few perspectives that might help you.
Module loading is still not supported on modern browsers by default, and you'd need to set special flags in order to enable it (which the users of your app probably won't do).
If you insist on using import and export, you'd need Webpack. And most certainly Babel (or any other ES6 transpiler, e.g. Buble) as well.
If you prefer module.exports, then you'd need Browserify. It enables support for CommonJS in browser environments.
If neither is doable, then your best bet is defining Vue components in global scope. You can split them across separate files, and import each with a <script> individually. Definitely not the cleanest approach.
Single file components typically go inside of .vue files, but either way they require vue-loader which can be added and configured (again) with a bundler.
Last option is to just use an existing setup in place, if there is any (is there?). If you already have RequireJS, UMD, or something similar in place, adjust your components to fit that. Otherwise, use <script>s.
You are trying to do something which is not possible. Vue Single file components are not supported as raw component file by web browsers. The single file component is supposed to be compiled.
Please see this for more:
https://v2.vuejs.org/v2/guide/single-file-components.html
In Webpack, each file can be transformed by a “loader” before being included in the bundle, and Vue offers the vue-loader plugin to translate single-file (.vue) components.
A vue single file component is first "translated" (compiled) to pure javascript code which is use-able by browsers.

Categories