• Stars
    star
    1,608
  • Rank 27,923 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Minimal, unopinionated static site generator powered by webpack

Build Status Coverage Status Dependency Status npm

static site generator webpack plugin

Minimal, unopinionated static site generator powered by webpack.

Bring the world of server rendering to your static build process. Either provide an array of paths to be rendered, or crawl your site automatically, and a matching set of index.html files will be rendered in your output directory by executing your own custom, webpack-compiled render function.

This plugin works particularly well with universal libraries like React and React Router since it allows you to pre-render your routes at build time, rather than requiring a Node server in production.

Install

$ npm install --save-dev static-site-generator-webpack-plugin

Usage

Ensure you have webpack installed, e.g. npm install -g webpack

webpack.config.js

const StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');

module.exports = {

  entry: './index.js',

  output: {
    filename: 'index.js',
    path: 'dist',
    /* IMPORTANT!
     * You must compile to UMD or CommonJS
     * so it can be required in a Node context: */
    libraryTarget: 'umd'
  },

  plugins: [
    new StaticSiteGeneratorPlugin({
      paths: [
        '/hello/',
        '/world/'
      ],
      locals: {
        // Properties here are merged into `locals`
        // passed to the exported render function
        greet: 'Hello'
      }
    })
  ]

};

index.js

Sync rendering:

module.exports = function render(locals) {
  return '<html>' + locals.greet + ' from ' + locals.path + '</html>';
};

Async rendering via callbacks:

module.exports = function render(locals, callback) {
  callback(null, '<html>' + locals.greet + ' from ' + locals.path + '</html>');
};

Async rendering via promises:

module.exports = function render(locals) {
  return Promise.resolve('<html>' + locals.greet + ' from ' + locals.path + '</html>');
};

Multi rendering

If you need to generate multiple files per render, or you need to alter the path, you can return an object instead of a string, where each key is the path, and the value is the file contents:

module.exports = function render() {
  return {
    '/': '<html>Home</html>',
    '/hello': '<html>Hello</html>',
    '/world': '<html>World</html>'
  };
};

Note that this will still be executed for each entry in your paths array in your plugin config.

Default locals

// The path currently being rendered:
locals.path;

// An object containing all assets:
locals.assets;

// Advanced: Webpack's stats object:
locals.webpackStats;

Any additional locals provided in your config are also available.

Crawl mode

Rather than manually providing a list of paths, you can use the crawl option to automatically crawl your site. This will follow all relative links and iframes, executing your render function for each:

module.exports = {

  ...

  plugins: [
    new StaticSiteGeneratorPlugin({
      crawl: true
    })
  ]
};

Note that this can be used in conjunction with the paths option to allow multiple crawler entry points:

module.exports = {

  ...

  plugins: [
    new StaticSiteGeneratorPlugin({
      crawl: true,
      paths: [
        '/',
        '/uncrawlable-page/'
      ]
    })
  ]
};

Custom file names

By providing paths that end in .html, you can generate custom file names other than the default index.html. Please note that this may break compatibility with your router, if you're using one.

module.exports = {

  ...

  plugins: [
    new StaticSiteGeneratorPlugin({
      paths: [
        '/index.html',
        '/news.html',
        '/about.html'
      ]
    })
  ]
};

Globals

If required, you can provide an object that will exist in the global scope when executing your render function. This is particularly useful if certain libraries or tooling you're using assumes a browser environment.

For example, when using Webpack's require.ensure, which assumes that window exists:

module.exports = {
  ...,
  plugins: [
    new StaticSiteGeneratorPlugin({
      globals: {
        window: {}
      }
    })
  ]
}

Asset support

template.ejs

<% css.forEach(function(file){ %>
<link href="<%- file %>" rel="stylesheet">
<% }); %>

<% js.forEach(function(file){ %>
<script src="<%- file %>" async></script>
<% }); %>

index.js

if (typeof global.document !== 'undefined') {
  const rootEl = global.document.getElementById('outlay');
  React.render(
    <App />,
    rootEl,
  );
}

export default (data) => {
  const assets = Object.keys(data.webpackStats.compilation.assets);
  const css = assets.filter(value => value.match(/\.css$/));
  const js = assets.filter(value => value.match(/\.js$/));
  return template({ css, js, ...data});
}

Specifying entry

This plugin defaults to the first chunk found. While this should work in most cases, you can specify the entry name if needed:

module.exports = {
  ...,
  plugins: [
    new StaticSiteGeneratorPlugin({
      entry: 'main'
    })
  ]
}

Compression support

Generated files can be compressed with compression-webpack-plugin, but first ensure that this plugin appears before compression-webpack-plugin in your plugins array:

const StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  ...

  plugins: [
    new StaticSiteGeneratorPlugin(...),
    new CompressionPlugin(...)
  ]
};

Related projects

  • react-router-to-array - useful for avoiding hardcoded lists of routes to render
  • gatsby - opinionated static site generator built on top of this plugin

License

MIT License

More Repositories

1

stellar.js

Stellar.js - Parallax scrolling made easy
JavaScript
4,642
star
2

redial

Universal data fetching and route lifecycle management for React etc.
JavaScript
1,104
star
3

react-themeable

Utility for making React components easily themeable
JavaScript
550
star
4

fathom

Fathom.js - Present JavaScript in its native environment.
JavaScript
527
star
5

redux-analytics

Analytics middleware for Redux
JavaScript
489
star
6

react-to-html-webpack-plugin

Webpack plugin that renders React components to HTML files
JavaScript
166
star
7

postcss-local-scope-example

Example usage of postcss-local-scope
JavaScript
136
star
8

presentation-build-wars-gulp-vs-grunt

CSS
77
star
9

tmpload

Asynchronous Template Loading and Caching for jQuery Templates
JavaScript
62
star
10

redux-tap

Simple side-effect middleware for Redux
JavaScript
58
star
11

remix-vanilla-extract-prototype

TypeScript
53
star
12

serviceworker-loader

ServiceWorker loader for Webpack
JavaScript
52
star
13

gulp-coveralls

Gulp plugin to send code coverage to Coveralls
JavaScript
45
star
14

web-app-manifest-loader

Web app manifest loader for webpack
JavaScript
41
star
15

isolated-scroll

Prevent scoll events from bubbling up to parent elements
HTML
40
star
16

nextjs-vanilla-extract-example

TypeScript
36
star
17

grunt-micro

Ensure your micro-framework stays micro
JavaScript
35
star
18

react-isolated-scroll

React component for isolated-scroll
JavaScript
34
star
19

figma-leading-trim

Figma plugin for trimming space above and below text elements
TypeScript
29
star
20

react-static-site-playground

WIP
JavaScript
26
star
21

jquery-html5data

$.html5data
JavaScript
22
star
22

presentation-a-state-of-change-object-observe

JavaScript
22
star
23

css-modules-in-js-demo

Working demo of using JavaScript as a CSS Modules preprocessor
JavaScript
21
star
24

astro-vanilla-extract-demo

Basic demo of Astro and vanilla-extract
Astro
18
star
25

Eventralize

jQuery Events for Object Oriented JavaScript
JavaScript
18
star
26

presentation-the-case-for-css-modules

HTML
15
star
27

node-lanyrd-scraper

Lanyrd event scraper for Node.js
JavaScript
14
star
28

allthethings.js

Let your array iterations read like actual sentences
JavaScript
11
star
29

fifteen-kilos-webpack-plugin

Bring the magic of fifteen-kilos to your entire project
HTML
11
star
30

instrument-methods

Simple object method instrumentation
JavaScript
11
star
31

react-fifteen-kilos

Bring the magic of fifteen-kilos to your entire React application
JavaScript
10
star
32

react-progressive-component-starter

WIP
JavaScript
9
star
33

presentation-a-unified-styling-language

HTML
8
star
34

reconomise

Crowd sourced local business support network and priority ranking system. 'Best Use of SAPI' at RHoK Melbourne June '12.
JavaScript
8
star
35

react-themeable-experiment

WIP
JavaScript
7
star
36

bespoke-remote-prototype

Prototype presentation for bespoke-remote
JavaScript
7
star
37

presentation-the-end-of-global-css

HTML
6
star
38

angular-delegator

Write smaller, cleaner AngularJS services
JavaScript
6
star
39

presentation-bespoke.js

DIY Presentations with Bespoke.js
JavaScript
5
star
40

batsignal

Help radiator for remote agile teams. Built using Meteor.
JavaScript
5
star
41

presentation-return-of-the-progressive-web

The Return of the Progressive Web
HTML
5
star
42

redux-hotjar

Declarative Hotjar tagging for Redux
JavaScript
4
star
43

stellar.js-site

Stellar.js Project Page
JavaScript
4
star
44

webpack-serviceworker-demo

Webpack Service Worker demo
JavaScript
4
star
45

presentation-first-class-styles

HTML
4
star
46

indiana

Experimental isomorphic JavaScript demo
JavaScript
3
star
47

bespoke-webpack-boilerplate

Bespoke.js boilerplate powered by Webpack
JavaScript
3
star
48

markdalgleish.com

My personal blog - built with Octopress
JavaScript
3
star
49

remix-vite-css-url-demo

Demo of Remix + Vite + .css?url
JavaScript
3
star
50

stateless-dtm

Purely stateless interface for Dynamic Tag Manager
JavaScript
3
star
51

twitface

Twitter avatar API client for Node.js
JavaScript
2
star
52

chook-jstestdriver

JsTestDriver adapter for Chook, the headless, framework-agnostic unit test runner for Node.js
JavaScript
2
star
53

chook

Headless, framework-agnostic unit test runner for Node.js
JavaScript
2
star
54

css-hooks-playground

Just playing around with CSS Hooks
TypeScript
2
star
55

remix-vite-cloudflare-workers-playground

Demo app using Remix with Vite on Cloudflare Workers
TypeScript
1
star
56

postcss-local-scope-inheritance-example

Example usage of postcss-local-scope with class inheritance
JavaScript
1
star
57

redux-helloworld

Just playing around with Redux
JavaScript
1
star
58

zenhub

Placeholder repo for my Zenhub mega-board
1
star
59

css-modules-selector-experiment

Exploration of non-class selectors in CSS Modules
JavaScript
1
star
60

cuecard

iPad-controlled presentation framework for Node.js
JavaScript
1
star
61

tmpload-site

tmpload Project Page
JavaScript
1
star
62

Eventralize-site

Eventralize Project Page
JavaScript
1
star
63

presentation-dawn-of-the-progressive-single-page-app

HTML
1
star
64

fathom-site

Fathom.js Project Page
JavaScript
1
star
65

cuecard-example

Example usage of Cuecard
JavaScript
1
star
66

kansas

Experimental stereoscopic rendering for React components
JavaScript
1
star
67

ducks-component-experiment

Experimental React component powered by Ducks
JavaScript
1
star
68

bespoke.js-site

Bespoke.js Project Page
CSS
1
star
69

preconstruct-node-esm-import-issue

JavaScript
1
star
70

presentation-a-bespoke-ecosystem

JavaScript
1
star
71

presentation-tabs

Ryan loses
CSS
1
star
72

baltic

Experimental continuous deployment with Codeship for Bespoke.js
JavaScript
1
star
73

presentation-web-components

Web Components: Why You're Already An Expert
JavaScript
1
star
74

bespoke-theme-prototype

CSS
1
star
75

angular-lisa-example

Sample app wiring AngularJS and Lisa together
JavaScript
1
star
76

balance-parens

Balance a string of parentheses.
JavaScript
1
star
77

chook-zombie

Experimental Zombie support for Chook
JavaScript
1
star
78

jquery-html5data-site

$.html5data Project Page
JavaScript
1
star
79

walletconnnect-deeplink-prompt-issue

TypeScript
1
star
80

melbcss-modules-hello-world

A simple CSS Modules example, extracted from a live coding demo at MelbCSS
JavaScript
1
star