react-static-webpack-plugin

2.1.0 • Public • Published

React Static Webpack Plugin

Build Status react-string-replace.js on NPM

Build full static sites using React, React Router and Webpack

This module can be added to exiting projects, but if you're looking to start coding right now check out the React Static Boilerplate.

Install

$ npm install --save-dev react-static-webpack-plugin

Usage

Simple Example

// webpack.config.js
const ReactStaticPlugin = require('react-static-webpack-plugin');
 
module.exports = {
 
  entry: {
    app: './client/index.js',
  },
 
  output: {
    path: path.join(__dirname, 'public'),
    filename: '[name].js',
    publicPath: '/',
  },
 
  plugins: [
    new ReactStaticPlugin({
      routes: './client/index.js',  // Path to routes file
      template: './template.js',    // Path to JSX template file
    }),
  ],
 
  // ... other config
 
};
// client/index.js
import React from 'react';
import { render } from 'react-dom';
import App from './components/App.js';
 
render(<App />, document.getElementById('root'));
 
// Be sure to export the React component so that it can be statically rendered
export default App;

Now when you run webpack you will see index.html in the output. Serve it statically and open it in any browser.

Multi-page sites with React Router

Creating sites with multiple static pages using React Router is very similar to the simple example, but instead of exporting any old React component export a <Route /> component:

// client/index.js
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
 
// Since we're rendering static files don't forget to use browser history.
// Server's don't get the URL hash during a request.
import createBrowserHistory from 'history/lib/createBrowserHistory';
 
// Import your routes so that you can pass them to the <Router /> component
import routes from './routes.js';
 
render(
  <Router routes={routes} history={browserHistory} />,
  document.getElementById('root')
);
// client/routes.js
import React from 'react';
import { Route } from 'react-router';
 
import {
  App,
  About,
  Products,
  Product,
  Contact,
  Nested,
} from './components';
 
const NotFound = () => <h4>Not found 😞</h4>;
 
export const routes = (
  <Route path='/' title='App' component={App}>
    <Route path='about' title='App - About' component={About} />
    <Route path='contact' title='App - Contact' component={Contact} />
    <Route path='products' title='App - Products' component={Products}>
      <Route path='product' title='App - Products - Product' component={Product}>
        <Route path='nested' title='App - Products - Product - Nested' component={Nested} />
      </Route>
    </Route>
    <Route path='*' title='404: Not Found' component={NotFound} />
  </Route>
);
 
export default routes;

NOTE: The title prop on the <Route /> components is totally optional but recommended. It will not affect your client side app, only the <title> tag of the generated static HTML.

Now you will see nested HTML files int the webpack output. Given our router example it would look something like this:

                     Asset       Size  Chunks             Chunk Names
                index.html  818 bytes          [emitted]
                    app.js     797 kB       0  [emitted]  app
                   app.css    8.28 kB       0  [emitted]  app
                about.html    1.05 kB          [emitted]
              contact.html    1.46 kB          [emitted]
             products.html    2.31 kB          [emitted]
      products/zephyr.html    2.45 kB          [emitted]
products/zephyr/nomad.html    2.53 kB          [emitted]
                  404.html  882 bytes          [emitted]

NOTE: When the plugin encounters <Route path='*' /> it will assume that this is the 404 page and will name it 404.html.

Full Example

For a full examples you can run locally, see the example/ directory or the React Static Boilerplate.

Generating index.html for every route

By default this plugin will generate a named HTML file for leaf routes, i.e. any route without child routes. Example:

<Route path='about' component={About} />
// -> 'about.html'

However you can also chose to opt in to generating an index.html file for every route by simply adding a trailing / to your path prop. Example:

// Notice the trailing slash below
//                ↓
<Route path='about/' component={About} />
// -> 'about/index.html'

See the deep route nesting example for a complete example of generating index.html files.

Rendering State React Components (Sort of like a browser)

This plugin uses JSDOM to render your components in a pseudo browser environment. This means that everything you expect in the browser should be available to you at render time. This means that code like this won't break your build:

class Comp extends React.Component {
  constructor() {
    this.width = window.innerWidth;
    this.height = window.innerHeight;
  }
 
  render() {
    const { width, height } = this;
    return (
      <div style={{ width, height, }} className='Comp' />
    );
  }
}

Since JSDOM provides a window object the React component above will be able to access the global window object just fine.

Current Limitations

This plugin does not currently support all the functionality of react router. Most notably it does not support dynamic route paths. For example:

<Route path='blog' component={Blog}>
  <Route path=':id' component={Post} />
</Route>

In a standard single page app when you hit the Post component you would probably look at the ID in the URL and fetch the appropriate post. However, to build static files we need all data available to us at the time of compilation, and in this case I have yet to come up with a clever way of passing dynamic data to the plugin and correctly mapping it to HTML files.

I have some thoughts on this and am actively exploring how it might work but nothing has been implemented yet. If you have any thoughts on what this might look like please open an issue and let me know!

API

new ReactStaticPlugin({ ...options })

routes (required)

Type: string

The path to your routes component. Your routes component should be exported either as routes or the default: './client/routes.js'

template (required)

Type: string

Path to the file that exports your template React component. Example: ./template.js

With this option you can provide the path to a custom React component that will render the layout for your static pages. The function will be passed an options object that will give you access to the page title and the rendered component:

// template.js
import React from 'react';
 
const Html = (props) => (
  <html lang='en'>
    <head>
      <meta charSet='utf-8' />
      <meta httpEquiv='X-UA-Compatible' content='IE=edge' />
      <meta name='viewport' content='width=device-width, minimum-scale=1.0' />
      <title>{props.title}</title>
      <script dangerouslySetInnerHTML={{ __html: 'console.log("analytics")' }} />
    </head>
    <body>
      <div id='root' dangerouslySetInnerHTML={{ __html: props.body }} />
      <script src='/app.js' />
    </body>
  </html>
);
 
export default Html;

NOTE: Your template component will be run through Webpack using whatever transformations or loaders you already have set up for the filetype specified. For example, if you are using babel for all JS files then your template file will be run through babel using whatever settings you have set up in .babelrc.

NOTE: You can pass arbitrary data to your template component by adding to the options object passed when you initialize the plugin:

new ReactStaticPlugin({
  routes: './client/index.js',
  template: './template.js',
 
  // Some arbitrary data...
  someData: 'Welcome to Webpack plugins',
}),

Then access the data within your template component using props:

// template.js
import React from 'react';
 
const Html = (props) => (
  <html lang='en'>
    <head>
      <title>{props.title}</title>
    </head>
    <body>
      <h1>{props.someData}</h1>
      <div id='root' dangerouslySetInnerHTML={{ __html: props.body }} />
      <script src='/app.js' />
    </body>
  </html>
);
 
export default Html;

The props object will have everything you passed in the options object to the plugin as well as:

  • body: A string of HTML to be rendered in the document.
  • title: A string that is passed from each of your Route components
  • manifest: An object mapping asset names to their generated output filenames. This will simply map asset names to themselves unless you add the webpack-manifest-plugin. Example usage: manifest['app.js']. See the section on the manifest option below.
  • initialState: If you pass the reduxStore option you will get access to the result of calling store.getState(). NOTE: Since this plugin makes no assumptions about the shape of your app state it is up to you to stringify it and place it in the DOM if you wish to use it.

reduxStore

Type: string

Default: undefined

The path to your Redux store. This option allows you to pass a store to react-static-webpack-plugin. This allows for Redux support. The store you pass in will be used in tandem with the react-redux <Provider store={store}> component to render your Redux app to a static site.

renderToStaticMarkup

Type: boolean

Default: false

Set to true to use render output code without extra DOM attributes such as data-reactid, that React uses internally. This is useful if you want to use the React Static Webpack Plugin as a simple static page generator, as stripping away the extra attributes can save lots of bytes.

manifest

Type: string

Default: 'manifest.json'

(Optional) The output filename of a manifest file if using the webpack-manifest-plugin. This is useful if you want to have access to the manifest within your template file so that you can easily implement long-term caching.

IMPORTANT NOTE: For this to work you MUST include the webpack-manifest-plugin before this static site plugin.

Example:

// webpack.config.js
module.exports = {
 
  // Other config...
 
  plugins: [
    // Other plugins...
 
    new ManifestPlugin(), // Important! This must come before the ReactStaticPlugin
    new ReactStaticPlugin({
      routes: './client/routes.js',
      template: './template.js',
    }),
  ],
};
// template.js
const React = require('react');
const T = React.PropTypes;
 
const Html = ({ title = 'Amazing Default Title', body, manifest }) => (
  <html lang='en'>
    <head>
      <meta charSet='utf-8' />
      <meta httpEquiv='X-UA-Compatible' content='IE=edge' />
      <meta name='viewport' content='width=device-width, initial-scale=1' />
      <title>{title}</title>
      <link rel='stylesheet' href={manifest['app.css']} />
    </head>
    <body>
      <div id='root' dangerouslySetInnerHTML={{ __html: body }} />
      <script src={manifest['app.js']} />
    </body>
  </html>
);
 
Html.propTypes = {
  title: T.string,
  body: T.string,
  manifest: T.object.isRequired,
};
 
module.exports = Html;

NOTE: In the above template file the href for the stylesheet as well as the src for the script tag are specified as keys on the manifest object.

Roadmap

  • Custom HTML layout option
  • Improved testing
  • JSX templating support
  • Redux support
  • Support for dynamic routes + data (i.e. <Route path='post/:id' />)
  • Custom 404 page filename option
  • Passing all props from <Route> components and React Router to your template component as props (See #12)

Development

The source for this plugin is transpiled using Babel. Most importantly this allows us to use JSX, but it also provides access to all ES6 features. During development you probably want to watch the source files and compile them whenever they change. To do this:

To watch

npm run watch

To build

npm run build

Make sure to run the project locally to be sure everything works as expected (we don't yet have a test suite). To do this link this repo locally using NPM. From the source directory:

npm link .

Then you can link it within any local NPM project:

Now when you require or import it you will get the local version.

npm link react-static-webpack-plugin

To test

First, make sure you've installed all the test dependencies. This means installing all node_modules within the example/ directory. You can do this with the provided script.

./install_test_dependencies.sh

Now you can run the tests:

npm test

Runs ESLint, Flow type checking and the suite of Wepback tests.

Running individual tests

If there is one specific test failing and you want to run it individually you can do so. Make sure you have ava installed globally:

npm install -g ava

Then you can run invidual tests by running a command similar to this. For example, to test only the Redux tests you can run:

NODE_ENV=production DEBUG=react-static-webpack-plugin* ava --verbose  ./example/redux/test.js

The DEBUG env variable tells the plugin to be very verbose in its logging output.

License

MIT © Ian Sinnott

Package Sidebar

Install

npm i react-static-webpack-plugin

Weekly Downloads

41

Version

2.1.0

License

MIT

Last publish

Collaborators

  • ian_sinn