• Stars
    star
    291
  • Rank 137,081 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 7 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

Abstracts universal consumption of application code base using webpack.

isomorphic-webpack

Travis build status Coveralls NPM version Canonical Code Style Twitter Follow

isomorphic-webpack

isomorphic-webpack is a program that runs server-side and enables rendering of the same code base client- and server-side.

Put it another way, it is a service for rendering webpack applications server-side. All that can be rendered client-side (e.g. React, Angular, etc. applications) will be processed server-side and served as static HTML.

Try it!

git clone [email protected]:gajus/isomorphic-webpack-demo.git
cd ./isomorphic-webpack-demo
npm install
export DEBUG=express:application,isomorphic-webpack
npm start

This will start the server on http://127.0.0.1:8000/.

$ curl http://127.0.0.1:8000/

<!doctype html>
<html>
  <head></head>
  <body>
    <div id='app'>
      <div class="app-___style___greetings" data-reactroot="" data-reactid="1" data-react-checksum="72097819">Hello, World!</div>
    </div>

    <script src='/static/app.js'></script>
  </body>
</html>

Goals


Table of contents

Setup

High-level abstraction

import {
	createIsomorphicWebpack
} from 'isomorphic-webpack';
import webpackConfiguration from './webpack.configuration';

createIsomorphicWebpack(webpackConfiguration);

API

/**
 * @see https://webpack.js.org/configuration/
 */
type WebpackConfigurationType = Object;

/**
 * @see https://github.com/gajus/gitdown#isomorphic-webpack-setup-high-level-abstraction-isomorphic-webpack-configuration
 */
type UserIsomorphicWebpackConfigurationType = {
  useCompilationPromise?: boolean
};

type IsomorphicWebpackType = {|
  /**
   * @see https://webpack.github.io/docs/node.js-api.html#compiler
   */
  +compiler: Compiler,
  +createCompilationPromise: Function,
  +evalBundleCode: Function,
  +formatErrorStack: Function
|};

createIsomorphicWebpack(webpackConfiguration: WebpackConfigurationType, isomorphicWebpackConfiguration: UserIsomorphicWebpackConfigurationType): IsomorphicWebpackType;

Isomorphic webpack configuration

{
  "additionalProperties": false,
  "properties": {
    "nodeExternalsWhitelist": {
      "description": "An array of paths to whitelist in the webpack `external` configuration. The default behaviour is to externalise all modules present in the `node_modules/` directory.",
      "items": {
        "oneOf": [
          {
            "type": "string"
          },
          {
            "instanceof": "RegExp"
          }
        ]
      },
      "type": "array"
    },
    "useCompilationPromise": {
      "description": "Toggles compilation observer. Enable this feature to use `createCompilationPromise`.",
      "type": "boolean"
    }
  },
  "type": "object"
}

If you have a requirement for a configuration, raise an issue describing your use case.

Handling errors

When a runtime error originates in a bundle, the stack trace refers to the code executed in the bundle (#4).

Use formatErrorStack to replace references to the VM code with the references resolved using the sourcemap, e.g.

const {
  formatErrorStack
} = createIsomorphicWebpack(webpackConfiguration);

app.get('*', isomorphicMiddleware);

app.use((err, req, res, next) => {
  console.error(formatErrorStack(err.stack));
});
ReferenceError: props is not defined
-   at TopicIndexContainer (evalmachine.<anonymous>:485:15)
+   at TopicIndexContainer (/src/client/containers/TopicIndexContainer/index.js:14:14)
    at WrappedComponent (/node_modules/react-css-modules/dist/wrapStatelessFunction.js:55:38)
    at /node_modules/react-dom/lib/ReactCompositeComponent.js:306:16
    at measureLifeCyclePerf (/node_modules/react-dom/lib/ReactCompositeComponent.js:75:12)
    at ReactCompositeComponentWrapper._constructComponentWithoutOwner (/node_modules/react-dom/lib/ReactCompositeComponent.js:305:14)
    at ReactCompositeComponentWrapper._constructComponent (/node_modules/react-dom/lib/ReactCompositeComponent.js:280:21)
    at ReactCompositeComponentWrapper.mountComponent (/node_modules/react-dom/lib/ReactCompositeComponent.js:188:21)
    at Object.mountComponent (/node_modules/react-dom/lib/ReactReconciler.js:46:35)
    at /node_modules/react-dom/lib/ReactServerRendering.js:45:36
    at ReactServerRenderingTransaction.perform (/node_modules/react-dom/lib/Transaction.js:140:20)

Note: References to a generated code that cannot be resolved in a source map are ignored (#5).

Reading list

FAQ

How to get started?

The easiest way to start is to analyse the demo application.

To start the server:

git clone [email protected]:gajus/isomorphic-webpack-demo.git
cd ./isomorphic-webpack-demo
npm install
export DEBUG=express:application,isomorphic-webpack
npm start

This will start the server on http://127.0.0.1:8000/.

open http://127.0.0.1:8000/

How does isomorphic-webpack work?

Refer to the Low-level abstraction documentation.

How to use webpack *-loader loader?

Loaders allow you to preprocess files as you require() or "load" them. [..] Loaders can transform files from a different language like, CoffeeScript to JavaScript, or inline images as data URLs.

– https://webpack.github.io/docs/loaders.html

isomorphic-webpack is simulating the browser environment to evaluate loaders that are designed to run in a browser, e.g. style-loader. Therefore, all webpack loaders work out of the box with isomorphic-webpack.

If you have found a loader that does not work, report an issue.

How does the hot-reloading work?

I have been asked a question:

I have setup https://github.com/gajus/isomorphic-webpack-demo and navigated to http://127.0.0.1:8000/. It printed 'Hello, World!'.

Then I have changed ./src/app/index.js to say Hello, HRM!. I was expecting the message 'Hello, World!' to change to 'Hello, HMR!' in the already open browser window. However, it didn't.

The message changed to 'Hello, HRM!' only after I have refreshed the browser window.

How is this hot-reloading?

I have used the term "hot-reloading" to describe a process where the webpack bundle is rebuilt every time a file in the project changes. The change will be visible on the next HTTP request.

It is "hot-reloading" in a sense that you do not need to restart the HTTP server every time you make a change to the application.

There is no logic that would force-refresh the page on completion of the compilation. There are several ways to achieve this, e.g. using a custom script that queries the backend. However, this does logic does not belong in isomorphic-webpack.

The purpose of the server-side rendering is to generate HTML response to a HTTP request. isomorphic-webpack does perform hot-reloading that satisfies this use case.

The primary purpose of hot module reloading (HRM) is to enable better developer experience. Given that it is a development feature, it is safe to assume that the developer is in control over the development environment. Therefore, to achieve HMR you need to implement the logic in your frontend application and configure webpack as described in the Hot module replacement with webpack guide.

How to differentiate between Node.js and browser environment?

Check for presence of ISOMORPHIC_WEBPACK variable.

Presence of ISOMORPHIC_WEBPACK indicates that code is executed using Node.js.

if (typeof ISOMORPHIC_WEBPACK === 'undefined') {
	// Browser
} else {
	// Node.js
}

How to enable logging?

isomorphic-webpack is using debug to log messages.

To enable logging, export DEBUG environment variable:

export DEBUG=isomorphic-webpack:*

How to subscribe to compiler events?

Using createIsomorphicWebpack result has a compiler property. compiler is an instance of a webpack Compiler. Use it to subscribe to all compiler events.

How to delay route initialisation until the first successful compilation?

See also:

Attempting to render a route server-side before the compiler has completed at least one compilation will produce an error, e.g.

+SyntaxError: /src/app/style.css: Unexpected token (1:0)
+> 1 | .greetings {
+    | ^
+  2 |   font-weight: bold;
+  3 | }
+  4 |
    at Parser.pp$5.raise (/node_modules/babylon/lib/index.js:4246:13)
    at Parser.pp.unexpected (/node_modules/babylon/lib/index.js:1627:8)
    at Parser.pp$3.parseExprAtom (/node_modules/babylon/lib/index.js:3586:12)
    at Parser.parseExprAtom (/node_modules/babylon/lib/index.js:6402:22)
    at Parser.pp$3.parseExprSubscripts (/node_modules/babylon/lib/index.js:3331:19)
    at Parser.pp$3.parseMaybeUnary (/node_modules/babylon/lib/index.js:3311:19)
    at Parser.pp$3.parseExprOps (/node_modules/babylon/lib/index.js:3241:19)
    at Parser.pp$3.parseMaybeConditional (/node_modules/babylon/lib/index.js:3218:19)
    at Parser.pp$3.parseMaybeAssign (/node_modules/babylon/lib/index.js:3181:19)
    at Parser.parseMaybeAssign (/node_modules/babylon/lib/index.js:5694:20)

The error will vary depending on what loaders your application code depends on.

Therefore, it is desirable to delay the first server-side render until the compiler has completed at least one compilation.

const {
  compiler
} = createIsomorphicWebpack(webpackConfiguration);

let routesAreInitialized;

compiler.plugin('done', () => {
  if (routesAreInitialized) {
    return;
  }

  routesAreInitialized = true;

  app.get('/', isomorphicMiddleware);
});

This pattern is demonstrated in the isomorphic-webpack-demo.

How to delay request handling while compilation is in progress?

See also:

WARNING!

Do not use this in production. This implementation has a large overhead.

It might be desirable to stall HTTP request handling until whatever in-progress compilation has completed. This ensures that during the development you do not receive a stale response.

To achieve this:

  • Enable compilation observer using useCompilationPromise configuration.
  • Use createCompilationPromise to create a promise that resolves when a current compilation completes.
  • Use the resulting promise to create a middleware that queues all HTTP requests until the promise is resolved.

Note:

You must enable this feature using useCompilationPromise configuration.

If you use createCompilationPromise without configuring useCompilationPromise, you will get an error:

"createCompilationPromise" feature has not been enabled.

Example usage:

const {
  createCompilationPromise
} = createIsomorphicWebpack(webpackConfiguration, {
  useCompilationPromise: true
});

app.use(async (req, res, next) => {
  await createCompilationPromise();

  next();
});

app.get('/', isomorphicMiddleware);

What makes isomorphic-webpack different from webpack-isomorphic-tools, universal-webpack, ...?

Feature isomorphic-webpack webpack-isomorphic-tools universal-webpack
Only one running node process.
Does not require a separate webpack configuration.
Enables use of all webpack loaders.
Server-side hot reloading of modules.
Supports stack trace.
Prevents serving stale data.
Does not override Node.js require().
Uses webpack target: "node".
Provides low-level API.

From a subjective perspective, isomorphic-webpack is a lot easier to setup than any of the existing alternatives.

I apologise in advance if I have misrepresented either of the frameworks.

Contact me to correct an error in the above comparison table, if you'd like to add another comparison criteria, or to add another framework.

I thought we agreed to use the term "universal"?

TL;DR: Isomorphism is the functional aspect of seamlessly switching between client- and server-side rendering without losing state. Universal is a term used to emphasize the fact that a particular piece of JavaScript code is able to run in multiple environments.

– https://medium.com/@ghengeveld/isomorphism-vs-universal-javascript-4b47fb481beb#.h7fikpuyk

isomorphic-webpack is a program that runs server-side and enables rendering of the same code base client- and server-side.

More Repositories

1

react-css-modules

Seamless mapping of class names to CSS modules inside of React components.
JavaScript
5,232
star
2

slonik

A Node.js PostgreSQL client with runtime and build time type safety, and composable SQL.
TypeScript
4,356
star
3

swing

A swipeable cards interface. The swipe-left/swipe-right for yes/no input. As seen in apps like Jelly and Tinder.
JavaScript
2,618
star
4

babel-plugin-react-css-modules

Transforms styleName to className using compile time CSS module resolution.
JavaScript
2,044
star
5

redux-immutable

redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.
TypeScript
1,880
star
6

eslint-plugin-flowtype

Flow type linting rules for ESLint.
JavaScript
1,078
star
7

prepack-webpack-plugin

A webpack plugin for prepack.
JavaScript
1,041
star
8

eslint-plugin-jsdoc

JSDoc specific linting rules for ESLint.
JavaScript
1,024
star
9

roarr

JSON logger for Node.js and browser.
TypeScript
1,024
star
10

turbowatch

Extremely fast file change detector and task orchestrator for Node.js.
TypeScript
901
star
11

table

Formats data into a string table.
TypeScript
871
star
12

usus

Webpage pre-rendering service. ⚡️
JavaScript
805
star
13

flow-runtime

A runtime type system for JavaScript with full Flow compatibility.
JavaScript
802
star
14

surgeon

Declarative DOM extraction expression evaluator. 👨‍⚕️
JavaScript
693
star
15

liqe

Lightweight and performant Lucene-like parser, serializer and search engine.
TypeScript
611
star
16

eslint-config-canonical

The most comprehensive ES code style guide.
JavaScript
536
star
17

write-file-webpack-plugin

Forces webpack-dev-server to write bundle files to the file system.
JavaScript
528
star
18

lightship

Abstracts readiness, liveness and startup checks and graceful shutdown of Node.js services running in Kubernetes.
TypeScript
514
star
19

gitdown

GitHub markdown preprocessor.
JavaScript
445
star
20

xhprof.io

GUI to analyze the profiling data collected using XHProf – A Hierarchical Profiler for PHP.
PHP
429
star
21

contents

Table of contents generator.
JavaScript
416
star
22

brim

View (minimal-ui) manager for iOS 8.
JavaScript
391
star
23

global-agent

Global HTTP/HTTPS proxy agent configurable using environment variables.
TypeScript
341
star
24

youtube-player

YouTube iframe API abstraction.
JavaScript
340
star
25

react-aux

A self-eradicating component for rendering multiple elements.
JavaScript
328
star
26

http-terminator

Gracefully terminates HTTP(S) server.
TypeScript
318
star
27

scream

Dynamic viewport management for mobile. Manage viewport in different states of device orientation. Scale document to fit viewport. Calculate the dimensions of the "minimal" iOS 8 view relative to your viewport width.
JavaScript
289
star
28

create-index

Creates ES6 ./index.js file in target directories that imports and exports all sibling files and directories.
JavaScript
279
star
29

graphql-deduplicator

A GraphQL response deduplicator. Removes duplicate entities from the GraphQL response.
JavaScript
278
star
30

gajus.com-blog

The contents of the http://gajus.com/blog/.
JavaScript
226
star
31

wholly

jQuery plugin used to select the entire table row and column in response to mouseenter and mouseleave events. Wholly supports table layouts that utilize colspan and rowspan.
JavaScript
204
star
32

puppeteer-proxy

Proxies Puppeteer Page requests.
JavaScript
195
star
33

canonical-reducer-composition

Spec for Canonical Reducer Composition design pattern.
188
star
34

angular-swing

AngularJS directive for Swing: A swipeable cards interface. The swipe-left/swipe-right for yes/no input. As seen in apps like Jelly and Tinder, and many others.
JavaScript
182
star
35

dindent

HTML indentation library for development and testing.
PHP
177
star
36

babel-plugin-graphql-tag

Compiles GraphQL tagged template strings using graphql-tag.
JavaScript
172
star
37

vlad

Input validation library promoting succinct syntax with extendable validators and multilingual support.
PHP
104
star
38

babel-plugin-log-deprecated

Adds a console.warn statement to the functions annotated with @deprecated tag.
JavaScript
103
star
39

redux-immutable-examples

A complete application showing use of redux-immutable.
JavaScript
103
star
40

eslint-plugin-canonical

ESLint rules for Canonical ruleset.
TypeScript
98
star
41

babel-preset-es2015-webpack

Babel preset for all es2015 plugins except babel-plugin-transform-es2015-modules-commonjs.
JavaScript
97
star
42

scalpel

A CSS selector parser.
JavaScript
95
star
43

eslint-plugin-sql

SQL linting rules for ESLint.
TypeScript
88
star
44

graphql-lazyloader

GraphQL directive that adds Object-level data resolvers.
TypeScript
88
star
45

orientationchangeend

The orientationchangeend event is fired when the orientation of the device has changed and the associated rotation animation has been complete.
JavaScript
78
star
46

bugger

Bugger is a collection of functions for debugging PHP code.
CSS
77
star
47

planton

Database-agnostic task scheduler.
TypeScript
77
star
48

pg-formatter

A PostgreSQL SQL syntax beautifier.
TypeScript
76
star
49

dora

Input generation library for value resolution, data persistence, templates, CSRF and protection from XSS.
CSS
73
star
50

react-css-modules-examples

Usage examples for react-css-modules.
JavaScript
72
star
51

format-graphql

Formats GraphQL schema definition language (SDL) document.
JavaScript
70
star
52

to-string-loader

to-string loader for webpack
JavaScript
64
star
53

interdependent-interactive-histograms

This is a helper function that utilises d3.js and Crossfilter to create interdependent interactive histograms.
JavaScript
60
star
54

extract-email-address

Extracts email address from an arbitrary text input.
JavaScript
59
star
55

babel-plugin-transform-function-composition

Syntactic sugar 🍧🍨🍦 for easy to read function composition. 🦄
JavaScript
58
star
56

preoom

Retrieves & observes Kubernetes Pod resource (CPU, memory) utilisation.
JavaScript
55
star
57

fuss

The Facebook SDK for PHP provides an interface to the Graph API.
PHP
53
star
58

postloader

A scaffolding tool for projects using DataLoader, Flow and PostgreSQL.
JavaScript
51
star
59

moa

MOA implements dynamically generated Active Record database abstraction.
PHP
50
star
60

extract-date

Extracts date from an arbitrary text input.
JavaScript
49
star
61

gitinfo

Gets information about a Git repository.
JavaScript
47
star
62

sister

Foundation for your emitter implementation. 202 reasons to not write your own implementation of event emitter.
JavaScript
45
star
63

react-outside-event

A higher order React component that attaches an event listener for events that occur outside of the component element.
JavaScript
44
star
64

babel-plugin-annotate-console-log

Annotates console.log call expression with information about the invocation context.
JavaScript
42
star
65

react-youtube-player

React component that encapsulates YouTube IFrame Player API and exposes player controls using the component properties.
JavaScript
40
star
66

bundle-dependencies

Generates bundledDependencies package.json value using values of the dependencies property. Updates package.json definition using the generated bundledDependencies value.
JavaScript
39
star
67

facebook-friend-rank

PHP class that can calculate who are the best user's friends. Data accuracy depends on the user activity and granted permissions.
PHP
39
star
68

waitehr

Waits for HTTP response and retries request until the expected response is received.
TypeScript
36
star
69

doll

Extended PDO with inline type hinting, deferred connection support, logging and benchmarking.
PHP
36
star
70

pie-chart

This is a helper function that utilises d3.js to create pie charts.
JavaScript
36
star
71

sguid

Signed Globally Unique Identifier (SGUID) generator.
JavaScript
34
star
72

prepack-loader

A webpack loader for prepack.
JavaScript
31
star
73

slonik-utilities

Utilities for manipulating data in PostgreSQL database using Slonik.
TypeScript
31
star
74

seeql

Real-time SQL profiler.
JavaScript
31
star
75

react-strict-prop-types

A higher order component that raises an error if component is used with an unknown property.
JavaScript
29
star
76

crack-json

Extracts all JSON objects from an arbitrary text document.
JavaScript
29
star
77

paggern

Pattern interpreter for generating random strings.
PHP
28
star
78

cluster-map

Abstracts execution of tasks in parallel using Node.js cluster.
JavaScript
27
star
79

roarr-cli

A CLI program for processing Roarr logs.
TypeScript
26
star
80

database-types

A generic type generator for various databases.
JavaScript
26
star
81

iapetus

Prometheus metrics server.
TypeScript
25
star
82

postgres-bridge

postgres/pg compatibility layer
TypeScript
25
star
83

roarr-browser-log-writer

Roarr log writer for use in a web browser.
TypeScript
23
star
84

require-new

Requires a new module object.
JavaScript
23
star
85

pan

Touch enabled implementation of WHATWG drag and drop mechanism.
JavaScript
23
star
86

tmdb

The Movie Database (TMDb) SDK.
JavaScript
22
star
87

pragmatist

A collection of tasks to standardize builds.
JavaScript
21
star
88

pianola

A declarative function composition and evaluation engine.
JavaScript
20
star
89

eslint-plugin-zod

Zod linting rules for ESLint.
TypeScript
20
star
90

approximate-now

Approximate (fast) current UNIX time.
TypeScript
20
star
91

babel-plugin-transform-export-default-name

Babel plugin that transforms default exports to named exports.
JavaScript
20
star
92

xfetch

A light-weight HTTP client for Node.js.
JavaScript
19
star
93

extract-time

Extracts time from an arbitrary text input.
JavaScript
19
star
94

override-require

Overrides Node.js module resolution logic.
JavaScript
18
star
95

fastify-webpack-hot

A Fastify plugin for serving files emitted by Webpack with Hot Module Replacement (HMR).
TypeScript
18
star
96

babel-plugin-lodash-modularize

Babel plugin that replaces lodash library import statement to individual module imports.
JavaScript
18
star
97

canonical

Canonical code style linter and formatter for JavaScript, SCSS, CSS and JSON.
JavaScript
18
star
98

semantic-url-parser

Extracts content information from known URL patterns.
TypeScript
17
star
99

extract-price

Extracts prices from an arbitrary text input.
JavaScript
17
star
100

async-request

async-request is a wrapper for request that uses ES7 async functions.
JavaScript
16
star