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

Optional custom rewrites #1

Merged
merged 2 commits into from
Jan 7, 2018
Merged
Changes from 1 commit
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
18 changes: 13 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
*/

class NetlifyServerPushPlugin {
constructor({ redirects }) {
this.redirects = Array.isArray(redirects) ? redirects : [];
Copy link
Owner

Choose a reason for hiding this comment

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

Here rather then falling back to [] every time I think we should throw an error if the user does not provide redirects as Array. i.e we should check

  • if a user provided redirects value
    • if its type is Array then assign it to this.redirects
    • else throw an error asking the user to provide it as Array.
  • else assign this.redirects to []

What do you say?

}

apply(compiler) {
compiler.plugin('emit', (compilation, callback) => {
const routes = [];
Expand All @@ -26,15 +30,17 @@ class NetlifyServerPushPlugin {
let headers =
'/*\n\tCache-Control: public, max-age=3600, no-cache\n\tAccess-Control-Max-Age: 600\n/sw.js\n\tCache-Control: private, no-cache\n/*.chunk.*.js\n\tCache-Control: public, max-age=31536000';

const redirects = `/* /index.html 200`;
const redirects = `${this.redirects.join('\n')}\n/* /index.html 200`;

routes.forEach(filename => {
const path = filename
.replace(/route-/, '/')
.replace(/\.chunk(\.\w+)?\.js$/, '')
.replace(/\/home/, '/');
const routeJs = `Link: </${filename}>; rel=preload; as=script`;
headers = `${headers}\n${path}\n\t${mainCss}\n\t${mainJs}\n\t${routeJs}`;
headers = `${headers}\n${path}\n\t${mainCss}\n\t${mainJs}\n\t${
routeJs
}`;
});

compilation.assets._headers = {
Expand All @@ -60,11 +66,13 @@ class NetlifyServerPushPlugin {
}
}

module.exports = function(config) {
module.exports = function(config, options = {}) {
if (!config || !config.plugins) {
throw new Error('You need to pass the webpack config to preact-cli-plugin-netlify!');
throw new Error(
'You need to pass the webpack config to preact-cli-plugin-netlify!',
);
}
config.plugins.push(new NetlifyServerPushPlugin());
config.plugins.push(new NetlifyServerPushPlugin(options));
const plugins = config.plugins;
for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
const plugin = plugins[pluginIndex];
Expand Down