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

Route Based Code Splitting #265

Merged
merged 17 commits into from
Jun 4, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
55 changes: 55 additions & 0 deletions greenwood.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,61 @@ module.exports = {
{ rel: 'icon', href: FAVICON_HREF },
{ name: 'google-site-verification', content: '4rYd8k5aFD0jDnN0CCFgUXNe4eakLP4NnA18mNnK5P0' }
],
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 6,
maxInitialRequests: 4,
automaticNameDelimiter: '~',
automaticNameMaxLength: 30,
cacheGroups: {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, We should be doing this in webpack.config.common.js for the user by default.

And also do some sort of dynamic creation of cacheGroups here like we do in webpack.config.common.js with NormalModuleReplaclementPlugin.

Copy link
Member Author

@hutchgrant hutchgrant Dec 10, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking along the lines of similar to a plugin. If a developer wants custom split routes, they can configure it however they please. But I also agree we should be doing it by default as well.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I would still like to see this done dynamically generated based on the folders set in the users pages/ directory for now. Easy enough for us to make another issue for thinking about how to make it a public API, likely hand in hand with being able to allow our Graph to also go "deeper" than a depth of one:

about: {
test(module, chunks) {
const regexp = /about/i;
const result = `${module.name || ''}`.match(regexp) || chunks.some(chunk => `${chunk.name || ''}`.match(regexp));

return result;
},
name: 'about',
chunks: 'all'
},
docs: {
test(module, chunks) {
const regexp = /docs/i;
const result = `${module.name || ''}`.match(regexp) || chunks.some(chunk => `${chunk.name || ''}`.match(regexp));

return result;
},
name: 'docs',
chunks: 'all'
},
gettingStarted: {
test(module, chunks) {
const regexp = /getting-started/i;
const result = `${module.name || ''}`.match(regexp) || chunks.some(chunk => `${chunk.name || ''}`.match(regexp));

return result;
},
name: 'getting-started',
chunks: 'all'
},
plugins: {
test(module, chunks) {
const regexp = /plugins/i;
const result = `${module.name || ''}`.match(regexp) || chunks.some(chunk => `${chunk.name || ''}`.match(regexp));

return result;
},
name: 'plugins',
chunks: 'all'
}
}
}
},

plugins: [
...pluginGoogleAnalytics({
analyticsId: 'UA-147204327-1'
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@
"nyc": "^14.0.0",
"rimraf": "^2.6.3"
}
}
}
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
17 changes: 9 additions & 8 deletions packages/cli/src/config/babel.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module.exports = {

// https://github.com/babel/babel/issues/9937#issuecomment-489352549
sourceType: 'unambiguous',

// https://github.com/babel/babel/issues/8731#issuecomment-426522500
ignore: [/[\/\\]core-js/, /@babel[\/\\]runtime/],

Expand All @@ -12,12 +12,12 @@ module.exports = {
// https://babeljs.io/docs/en/babel-preset-env
'@babel/preset-env',
{

// https://babeljs.io/docs/en/babel-preset-env#usebuiltins
useBuiltIns: 'entry',

// https://babeljs.io/docs/en/babel-preset-env#corejs
corejs: {
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
corejs: {
version: 3,
proposals: true
},
Expand All @@ -31,9 +31,10 @@ module.exports = {
// https://github.com/babel/babel/issues/8829#issuecomment-456524916
plugins: [
[
'@babel/plugin-transform-runtime', {
regenerator: true
}
'@babel/plugin-transform-runtime', {
regenerator: true
},
'@babel/plugin-syntax-dynamic-import'
]
]

Expand Down
7 changes: 5 additions & 2 deletions packages/cli/src/config/webpack.config.common.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ const getUserWorkspaceDirectories = (source) => {
const mapUserWorkspaceDirectories = (directoryPath, userWorkspaceDirectory) => {
const directoryName = directoryPath.replace(`${userWorkspaceDirectory}/`, '');
const userWorkspaceDirectoryRoot = userWorkspaceDirectory.split('/').slice(-1);

return new webpack.NormalModuleReplacementPlugin(
// https://github.com/ProjectEvergreen/greenwood/issues/132
new RegExp(`\\.\\.\\/${directoryName}.+$(?<!\.js)|${userWorkspaceDirectoryRoot}\\/${directoryName}.+$(?<!\.js)`),
(resource) => {

// workaround to ignore cli/templates default imports when rewriting
if (!new RegExp('\/cli\/templates').test(resource.content)) {
resource.request = resource.request.replace(new RegExp(`\\.\\.\\/${directoryName}`), directoryPath);
Expand Down Expand Up @@ -87,6 +87,7 @@ module.exports = ({ config, context }) => {
output: {
path: path.join(context.publicDir, '.', config.publicPath),
filename: '[name].[hash].bundle.js',
chunkFilename: '[name].[hash].bundle.js',
publicPath: config.publicPath
},

Expand Down Expand Up @@ -126,6 +127,8 @@ module.exports = ({ config, context }) => {
}]
},

optimization: config.optimization,
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved

plugins: [
new HtmlWebpackPlugin({
filename: path.join(context.publicDir, context.indexPageTemplate),
Expand Down
7 changes: 6 additions & 1 deletion packages/cli/src/lifecycles/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ let defaultConfig = {
publicPath: '/',
title: 'Greenwood App',
meta: [],
optimization: {},
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
plugins: [],
themeFile: 'theme.css'
};
Expand All @@ -24,7 +25,7 @@ module.exports = readAndMergeConfig = async() => {

if (await fs.exists(path.join(process.cwd(), 'greenwood.config.js'))) {
const userCfgFile = require(path.join(process.cwd(), 'greenwood.config.js'));
const { workspace, devServer, publicPath, title, meta, plugins, themeFile } = userCfgFile;
const { workspace, devServer, publicPath, title, meta, plugins, themeFile, optimization } = userCfgFile;

// workspace validation
if (workspace) {
Expand Down Expand Up @@ -96,6 +97,10 @@ module.exports = readAndMergeConfig = async() => {
customConfig.themeFile = themeFile;
}

if (optimization && Object.keys(optimization).length > 0) {
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
customConfig.optimization = optimization;
}

if (devServer && Object.keys(devServer).length > 0) {

if (devServer.host) {
Expand Down
13 changes: 12 additions & 1 deletion packages/cli/src/lifecycles/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ const createGraphFromPages = async (pagesDir, config) => {
// set <title></title> element text, override with markdown title
title = title || config.title;

// create webpack chunk name based on route and page name
const routes = route.lastIndexOf('/') === route.length - 1 && route.lastIndexOf('/') > 0
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
? route.substring(1, route.length - 1).split('/')
: route.substring(1, route.length).split('/');
let chunkName = 'page';

routes.map(subDir => {
chunkName += '--' + subDir;
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
});

/*
* Variable Definitions
*----------------------
Expand All @@ -78,9 +88,10 @@ const createGraphFromPages = async (pagesDir, config) => {
* imported into app.js root component
* title: the head <title></title> text
* meta: og graph meta array of objects { property/name, content }
* chunkName: generated chunk name for webpack bundle
*/

pages.push({ mdFile, label, route, template, filePath, fileName, relativeExpectedPath, title, meta });
pages.push({ mdFile, label, route, template, filePath, fileName, relativeExpectedPath, title, meta, chunkName });
}
if (stats.isDirectory()) {
await walkDirectory(filePath);
Expand Down
28 changes: 10 additions & 18 deletions packages/cli/src/lifecycles/scaffold.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const writePageComponentsFromTemplate = async (compilation) => {
let relPageDir = file.filePath.substring(context.pagesDir.length, file.filePath.length);
let pagePath = '';
const pathLastBackslash = relPageDir.lastIndexOf('/');

pagePath = path.join(context.scratchDir, file.fileName); // non-nested default

if (pathLastBackslash !== 0) {
Expand Down Expand Up @@ -89,30 +89,25 @@ const writePageComponentsFromTemplate = async (compilation) => {

};

const writeListImportFile = async (compilation) => {
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
const importList = compilation.graph.map(file => {
return `import ${file.relativeExpectedPath};\n`;
});

// Create app directory so that app-template relative imports are correct
const appDir = path.join(compilation.context.scratchDir, 'app');

await fs.ensureDir(appDir);
return await fs.writeFile(path.join(appDir, './list.js'), importList.join(''));
};

const writeRoutes = async(compilation) => {
return new Promise(async (resolve, reject) => {
try {
let data = await fs.readFile(compilation.context.appTemplatePath, 'utf8');

const routes = compilation.graph.map(file => {
return `<lit-route path="${file.route}" component="eve-${file.label}"></lit-route>\n\t\t\t\t`;
return `<lit-route
path="${file.route}"
component="eve-${file.label}"
.resolve="\${() => import(/* webpackChunkName: "${file.chunkName}" */ ${file.relativeExpectedPath})}"
loading="eve-loading"></lit-route>\n\t\t\t\t`;
});

const result = data.toString().replace(/MYROUTES/g, routes.join(''));
// Create app directory so that app-template relative imports are correct
const appDir = path.join(compilation.context.scratchDir, 'app');

await fs.writeFile(path.join(compilation.context.scratchDir, 'app', './app.js'), result);
await fs.ensureDir(appDir);
await fs.writeFile(path.join(appDir, './app.js'), result);

resolve();
} catch (err) {
Expand Down Expand Up @@ -145,9 +140,6 @@ module.exports = generateScaffolding = async (compilation) => {
console.log('Generate pages from templates...');
await writePageComponentsFromTemplate(compilation);

console.log('Writing imports for md...');
await writeListImportFile(compilation);

console.log('Writing Lit routes...');
await writeRoutes(compilation);

Expand Down
1 change: 0 additions & 1 deletion packages/cli/src/templates/app-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ const store = createStore(
compose(lazyReducerEnhancer(combineReducers), applyMiddleware(thunk)));

import '../index/index.js';
import './list';

connectRouter(store);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ const store = createStore(
compose(lazyReducerEnhancer(combineReducers), applyMiddleware(thunk)));

import '../index/index.js';
import './list';

connectRouter(store);

Expand Down
25 changes: 25 additions & 0 deletions www/components/loading/loading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { html, LitElement } from 'lit-element';
import './spinner';

class loading extends LitElement {
render() {
return html`
<style>
div {
padding-top:50px;
height: calc(100vh - 110px);
}
h1 {
padding: 30px;
text-align:center;
}
</style>
<div>
<eve-spinner size="100px"></eve-spinner>
<h1>Loading...</h1>
</div>
`;
}
}

customElements.define('eve-loading', loading);
38 changes: 38 additions & 0 deletions www/components/loading/spinner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { html, LitElement } from 'lit-element';

class spinner extends LitElement {

static get properties() {
return {
size: {
type: String
}
};
}

render() {
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
return html`
<style>
.spinner {
width: ${this.size};
padding: 10px;
margin-left:auto;
margin-right:auto;
}
</style>
<div class="spinner">
<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="${this.size}"
height="${this.size}" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve">
<path fill="#000"
d="M43.935,25.145c0-10.318-8.364-18.683-18.683-18.683c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615c8.072,0,14.615,6.543,14.615,14.615H43.935z"
transform="rotate(190.358 25 25)">
<animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animateTransform>
</path>
</svg>
</div>
`;
}
}

customElements.define('eve-spinner', spinner);
35 changes: 35 additions & 0 deletions www/templates/app-template.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { html, LitElement } from 'lit-element';
import { connectRouter } from 'lit-redux-router';
import { applyMiddleware, createStore, compose as origCompose, combineReducers } from 'redux';
import { lazyReducerEnhancer } from 'pwa-helpers/lazy-reducer-enhancer.js';
import thunk from 'redux-thunk';
import '../components/header/header';
import '../components/footer/footer';
import '../components/loading/loading';

// eslint-disable-next-line no-underscore-dangle
const compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || origCompose;

// eslint-disable-next-line
const store = createStore(
(state, action) => state, // eslint-disable-line
compose(lazyReducerEnhancer(combineReducers), applyMiddleware(thunk)));

import '../index/index.js';

connectRouter(store);

class AppComponent extends LitElement {
render() {
return html`
<div class='wrapper'>
Copy link
Member

@thescientist13 thescientist13 May 1, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems a shame we need a custom app-template.js just for a few lines of HTML. 🤔

I wonder if we could inherit from Greenwoood's AppComponent and just override just the render method somehow??? That would be pretty slick...

import { html } from 'lit-html';
import { AppComponent } from `@greenwood/cli/src/templates/app-component';

class GreenwoodAppComponent extends AppComponent {

  render() {
    return html`
      <custom-code-goes-here/>
    `;
  }
}

can probably be another issue, but would be good to play around with it now just to see what's possible, just to understand what can / can't be done.

<eve-header></eve-header>
MYROUTES
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
<lit-route><h1>404 Not found</h1></lit-route>
<eve-footer></eve-footer>
</div>
`;
}
}

customElements.define('eve-app', AppComponent);
Loading