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 10 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
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
**/node_modules/**
!.eslintrc.js
!.mocharc.js
!.mocharc.js
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
44 changes: 44 additions & 0 deletions greenwood.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,50 @@ module.exports = {
{ rel: 'icon', href: FAVICON_HREF },
{ name: 'google-site-verification', content: '4rYd8k5aFD0jDnN0CCFgUXNe4eakLP4NnA18mNnK5P0' }
],
optimization: {
splitChunks: {
chunks: 'all',
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'
},
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'
},
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'
},
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'
}
}
}
},

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 @@ -33,4 +33,4 @@
"nyc": "^14.0.0",
"rimraf": "^2.6.3"
}
}
}
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
10 changes: 5 additions & 5 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 Down
2 changes: 2 additions & 0 deletions packages/cli/src/config/webpack.config.common.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,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: 'My 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
14 changes: 13 additions & 1 deletion packages/cli/src/lifecycles/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ const createGraphFromPages = async (pagesDir, config) => {
// set <title></title> element text, override with markdown title
title = 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 @@ -90,6 +100,7 @@ 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
*/
const customData = attributes;

Expand Down Expand Up @@ -135,7 +146,8 @@ const createGraphFromPages = async (pagesDir, config) => {
fileName,
relativeExpectedPath,
title,
meta
meta,
chunkName
};
}

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 @@ -39,7 +39,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 @@ -71,30 +71,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 @@ -127,9 +122,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
9 changes: 4 additions & 5 deletions packages/cli/src/templates/app-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const store = createStore((state) => state,
);

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

connectRouter(store);

Expand Down Expand Up @@ -59,7 +58,7 @@ class AppComponent extends LitElement {
meta.forEach(metaItem => {
const metaType = metaItem.rel // type of meta
? 'rel'
: metaItem.name
: metaItem.name
hutchgrant marked this conversation as resolved.
Show resolved Hide resolved
? 'name'
: 'property';
const metaTypeValue = metaItem[metaType]; // value of the meta
Expand All @@ -72,16 +71,16 @@ class AppComponent extends LitElement {
meta.setAttribute('rel', metaTypeValue);
meta.setAttribute('href', metaItem.href);
} else {
const metaContent = metaItem.property === 'og:url'
? `${metaItem.content}${currentPage.link}`
const metaContent = metaItem.property === 'og:url'
? `${metaItem.content}${currentPage.link}`
: metaItem.content;

meta.setAttribute(metaType, metaItem[metaType]);
meta.setAttribute('content', metaContent);
}

const oldmeta = header.querySelector(`[${metaType}="${metaTypeValue}"]`);

// rehydration
if (oldmeta) {
header.replaceChild(meta, oldmeta);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const store = createStore(
compose(lazyReducerEnhancer(combineReducers), applyMiddleware(thunk)));

import '../index/index';
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);
Loading