Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: loadable components with partial js loading #17

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ module.exports = api => {
'@babel/plugin-transform-runtime',
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-numeric-separator',
'@babel/plugin-proposal-throw-expressions'
'@babel/plugin-proposal-throw-expressions',
'@loadable/babel-plugin'
];

const basePresets = [];
Expand Down
62 changes: 34 additions & 28 deletions lib/cli.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import arg from 'arg';
import fs from 'fs';
import path from 'path';
import clc from "cli-color";
import clc from 'cli-color';
import { spawn } from 'child_process';

import normalizeUrl from './os';
Expand All @@ -19,10 +19,10 @@ function parseArgumentsIntoOptions(rawArgs) {
'--no-bundle': Boolean,
'--analyze': Boolean,
'--port': Number,
'--ssr': Boolean,
'--ssr': Boolean
},
{
argv: rawArgs.slice(2),
argv: rawArgs.slice(2)
}
);
const argsList = removeUnneccesaryValueInObject({
Expand All @@ -32,17 +32,18 @@ function parseArgumentsIntoOptions(rawArgs) {
noBundle: args['--no-bundle'],
analyze: args['--analyze'],
configFile: args['--config'],
ssr: args['--ssr'],
ssr: args['--ssr']
});

return argsList;
}

function getVoltranConfigs(configFile) {
const normalizePath = normalizeUrl(path.resolve(__dirname));
const dirName = normalizePath.indexOf('node_modules') > -1 ?
normalizePath.split('/node_modules')[0] :
normalizePath.split('voltran/lib')[0] + 'voltran';
const normalizePath = normalizeUrl(path.resolve(__dirname));
const dirName =
normalizePath.indexOf('node_modules') > -1
? normalizePath.split('/node_modules')[0]
: `${normalizePath.split('voltran/lib')[0]}voltran`;
const voltranConfigs = require(path.resolve(dirName, configFile));

return voltranConfigs;
Expand All @@ -68,35 +69,40 @@ function runDevelopmentMode() {
function runProductionMode(voltranConfigs, onlyBundle) {
const bundle = require('../src/tools/bundle');

bundle()
.then((res) => {
console.log(clc.green('Bundle is completed.\n',`File: ${voltranConfigs.distFolder}/server/server.js`));
bundle().then(() => {
console.log(
clc.green('Bundle is completed.\n', `File: ${voltranConfigs.distFolder}/server/server.js`)
);

if (!onlyBundle) {
serve(voltranConfigs);
}
});
if (!onlyBundle) {
serve(voltranConfigs);
}
});
}

function serve(voltranConfigs) {
console.log(clc.green('Project Serve is starting...'));

const out = spawn('node', [
'-r',
'source-map-support/register',
'--max-http-header-size=20480',
`${voltranConfigs.distFolder}/server/server.js`
], {env: {'NODE_ENV': 'production', ...process.env}});
const out = spawn(
'node',
[
'-r',
'source-map-support/register',
'--max-http-header-size=20480',
`${voltranConfigs.distFolder}/server/server.js`
],
{ env: { NODE_ENV: 'production', ...process.env } }
);

out.stdout.on('data', (data) => {
out.stdout.on('data', data => {
console.log(data.toString());
});

out.stderr.on('data', (data) => {
out.stderr.on('data', data => {
console.error(data.toString());
});

out.on('close', (code) => {
out.on('close', code => {
console.log(`child process exited with code ${code}`);
});
}
Expand All @@ -123,17 +129,17 @@ export function cli(args) {
if (isValid) {
const createdConfig = `module.exports = ${JSON.stringify(mergeAllConfigs)}`;

fs.writeFile(path.resolve(__dirname, '../voltran.config.js'), createdConfig, function (err) {
fs.writeFile(path.resolve(__dirname, '../voltran.config.js'), createdConfig, function(err) {
if (err) throw err;

console.log('File is created successfully.', mergeAllConfigs.dev);

if (mergeAllConfigs.dev) {
runDevelopmentMode();
} else {
argumentList.noBundle ?
serve(voltranConfigs) :
runProductionMode(mergeAllConfigs, argumentList.bundle);
argumentList.noBundle
? serve(voltranConfigs)
: runProductionMode(mergeAllConfigs, argumentList.bundle);
}
});
} else {
Expand Down
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
"@babel/plugin-transform-runtime": "7.10.4",
"@babel/preset-env": "7.14.4",
"@babel/preset-react": "7.0.0",
"@researchgate/react-intersection-observer": "1.0.3",
"@loadable/babel-plugin": "^5.12.0",
"@loadable/component": "^5.12.0",
"@loadable/server": "^5.12.0",
"@loadable/webpack-plugin": "^5.12.0",
"arg": "^4.1.3",
"assets-webpack-plugin": "3.8.4",
"async": "^3.2.0",
Expand All @@ -37,7 +40,6 @@
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "10.0.1",
"babel-loader": "^8.0.4",
"classnames": "2.2.6",
"clean-webpack-plugin": "1.0.0",
"cli-color": "^2.0.0",
"compose-middleware": "5.0.0",
Expand All @@ -51,18 +53,17 @@
"eslint": "6.1.0",
"eslint-config-airbnb": "18.0.1",
"eslint-config-prettier": "6.3.0",
"eslint-plugin-babel": "^5.3.1",
"eslint-plugin-import": "^2.19.1",
"eslint-plugin-jsx-a11y": "6.2.3",
"eslint-plugin-prettier": "3.1.1",
"eslint-plugin-react": "7.14.3",
"eslint-plugin-react-hooks": "^4.2.0",
"esm": "^3.2.25",
"file-loader": "1.1.11",
"helmet": "3.21.3",
"hiddie": "^1.0.0",
"husky": "^3.1.0",
"identity-obj-proxy": "3.0.0",
"intersection-observer": "0.7.0",
"js-cookie": "^2.2.1",
"lodash": "4.17.19",
"mini-css-extract-plugin": "0.4.4",
"newrelic": "^6.13.0",
Expand All @@ -78,7 +79,6 @@
"prop-types": "15.6.2",
"query-string": "6.10.1",
"react": "16.12.0",
"react-autosuggest": "9.4.3",
"react-dom": "16.12.0",
"react-hot-loader": "^4.12.18",
"react-router": "5.1.2",
Expand Down
15 changes: 8 additions & 7 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,31 @@ import cluster from 'cluster';
import logger from './universal/utils/logger';
import Hiddie from 'hiddie';
import http from 'http';
import voltranConfig from '../voltran.config';
import prom from 'prom-client';
import {HTTP_STATUS_CODES} from './universal/utils/constants';

import voltranConfig from '../voltran.config';
import { HTTP_STATUS_CODES } from './universal/utils/constants';

const enablePrometheus = voltranConfig.monitoring.prometheus;

function triggerMessageListener(worker) {
worker.on('message', function (message) {
worker.on('message', function(message) {
if (message?.options?.forwardAllWorkers) {
sendMessageToAllWorkers(message);
}
});
}

function sendMessageToAllWorkers(message) {
Object.keys(cluster.workers).forEach(function (key) {
Object.keys(cluster.workers).forEach(function(key) {
const worker = cluster.workers[key];
worker.send({
msg: message.msg,
msg: message.msg
});
}, this);
}

cluster.on('fork', (worker) => {
cluster.on('fork', worker => {
triggerMessageListener(worker);
});

Expand All @@ -52,7 +53,7 @@ if (cluster.isMaster) {
return res.end(await aggregatorRegistry.clusterMetrics());
}
res.statusCode = HTTP_STATUS_CODES.NOT_FOUND;
res.end(JSON.stringify({message: 'not found'}));
res.end(JSON.stringify({ message: 'not found' }));
});

http.createServer(hiddie.run).listen(metricsPort, () => {
Expand Down
4 changes: 2 additions & 2 deletions src/universal/components/Html.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function componentClassName(componentName, context) {

function Html({
componentName,
children,
bodyHtml,
styleTags,
initialState,
fullWidth,
Expand All @@ -41,7 +41,7 @@ function Html({
class="${voltranConfig.prefix}-voltran-body voltran-body ${
isMobileFragment ? 'mobile' : ''
}${fullWidth ? 'full' : ''} ${componentClassName(componentName, context)}">
${children}
${bodyHtml}
</div>
<div>REPLACE_WITH_LINKS</div>
<div>REPLACE_WITH_SCRIPTS</div>
Expand Down
23 changes: 13 additions & 10 deletions src/universal/partials/withBaseComponent.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { loadableReady } from '@loadable/component';

import ClientApp from '../components/ClientApp';
import { WINDOW_GLOBAL_PARAMS } from '../utils/constants';
Expand Down Expand Up @@ -35,16 +36,18 @@ const withBaseComponent = (PageComponent, pathName) => {

const initialState = fragments[id].STATE;

ReactDOM.hydrate(
<ClientApp>
<PageComponent {...staticProps} initialState={initialState} history={history} />
</ClientApp>,
componentEl,
() => {
componentEl.style.pointerEvents = 'auto';
componentEl.setAttribute('voltran-hydrated', 'true');
}
);
loadableReady(() => {
ReactDOM.hydrate(
<ClientApp>
<PageComponent {...staticProps} initialState={initialState} history={history} />
</ClientApp>,
componentEl,
() => {
componentEl.style.pointerEvents = 'auto';
componentEl.setAttribute('voltran-hydrated', 'true');
}
);
});
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/universal/service/RenderService.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const renderHtml = (component, initialState, context) => {
return PureHtml(component.path, component.name, initialStateWithLocation);
}

const children = ReactDOMServer.renderToString(
const bodyHtml = ReactDOMServer.renderToString(
sheet.collectStyles(
<StaticRouter location={component.path} context={context}>
<ConnectedApp initialState={initialStateWithLocation} location={context} />
Expand All @@ -69,7 +69,7 @@ const renderHtml = (component, initialState, context) => {
return Html({
resultPath,
componentName: component.name,
children,
bodyHtml,
styleTags,
initialState: initialStateWithLocation,
fullWidth: component.fullWidth,
Expand Down
43 changes: 24 additions & 19 deletions src/universal/utils/baseRenderHtml.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,21 @@ const cleanAssetsPrefixFromAssetURI = assetURI => {

const cssContentCache = {};

if (process.env.NODE_ENV === 'production') {
Object.keys(assets).forEach(name => {
if (assets[name].css) {
cssContentCache[name] = fs.readFileSync(
path.resolve(
process.cwd(),
`${voltranConfig.publicDistFolder}/${cleanAssetsPrefixFromAssetURI(assets[name].css)}`
),
'utf8'
);
if (process.env.NODE_ENV === 'production' && assets.assetsByChunkName) {
Object.keys(assets.assetsByChunkName).
forEach(name => {
if (assets.assetsByChunkName[name] && Array.isArray(assets.assetsByChunkName[name]) && assets.assetsByChunkName[name].length > 0) {
assets.assetsByChunkName[name].map(fileName => {
if (fileName.endsWith('.css')) {
cssContentCache[name] = fs.readFileSync(
path.resolve(
process.cwd(),
`${voltranConfig.publicDistFolder}/${cleanAssetsPrefixFromAssetURI(fileName)}`,
),
'utf8',
);
}
});
}
});
}
Expand All @@ -33,12 +38,12 @@ const getScripts = (name, subComponentFiles) => {
const scripts = [
{
src: `${assetsBaseUrl}${assets.client.js}`,
isAsync: false
isAsync: false,
},
{
src: `${assetsBaseUrl}${assets[name].js}`,
isAsync: false
}
isAsync: false,
},
];
const mergedScripts =
subComponentFilesScripts && subComponentFilesScripts.length > 0
Expand All @@ -48,7 +53,7 @@ const getScripts = (name, subComponentFiles) => {
return mergedScripts;
};

const getStyles = async (name, subComponentFiles) => {
const getStyles = async(name, subComponentFiles) => {
const links = [];
const subComponentFilesStyles = subComponentFiles.styles;

Expand All @@ -59,7 +64,7 @@ const getStyles = async (name, subComponentFiles) => {
criticalStyleComponent:
process.env.NODE_ENV === 'production' && !voltranConfig.criticalCssDisabled
? cssContentCache[name]
: undefined
: undefined,
});
}

Expand All @@ -70,7 +75,7 @@ const getStyles = async (name, subComponentFiles) => {
criticalStyleComponent:
process.env.NODE_ENV === 'production' && !voltranConfig.criticalCssDisabled
? cssContentCache.client
: undefined
: undefined,
});
}

Expand All @@ -88,15 +93,15 @@ const getActiveComponent = name => {
return {
resultPath: path,
componentName: name,
url: path
url: path,
};
};

const createBaseRenderHtmlProps = async (name, subComponentFiles) => {
const createBaseRenderHtmlProps = async(name, subComponentFiles) => {
return {
scripts: getScripts(name, subComponentFiles),
links: await getStyles(name, subComponentFiles),
activeComponent: getActiveComponent(name)
activeComponent: getActiveComponent(name),
};
};

Expand Down
Loading