Coder Social home page Coder Social logo

yusinto / universal-hot-reload Goto Github PK

View Code? Open in Web Editor NEW
80.0 3.0 10.0 4.27 MB

Hot reload client and server webpack bundles for the ultimate development experience

License: MIT License

JavaScript 100.00%
universal-hot-reload universal hot reload reloading livereload live-reload live hot-reload hot-module-replacement

universal-hot-reload's Introduction

universal-hot-reload

Circle CI npm version npm downloads npm npm

Easily hot reload your server, client or universal apps ๐Ÿ‘

Why this package?

  • Setup hot reload for your app in four lines of code or less.
  • Supports server, client and universal hot reloads!
  • Works with react, typescript, graphql and nexus.

This should be used in development only!

Installation

yarn add universal-hot-reload -D

Quickstart: server only

To hot reload graphql servers and express servers without ssr, create index.js and server.js like below. For graphql, only express-graphql and apollo-server are supported for now.

index.js

const { serverHotReload } = require('universal-hot-reload');

// server.js is where you export your http.server instance (see below) 
serverHotReload(require.resolve('./server.js'));

server.js

// You'll need to export default an instance of http.server so universal-hot-reload
// can restart your server when changes are detected.

// For express or express-graphql
export default app.listen(PORT, () => console.log(`Listening at ${PORT}`));

// For apollo-server
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(() => console.log(`Listening at ${PORT}`));
export default server.httpServer;

Run your app:

node index.js

Quickstart: universal apps

To hot reload a universal app, create index.js like below and follow the same steps as Quickstart: server only.

index.js

const UniversalHotReload = require('universal-hot-reload').default;

// supply your own webpack configs
const serverConfig = require('../webpack.config.server.js');
const clientConfig = require('../webpack.config.client.js');

// the configs are optional, you can supply either one or both.
// if you omit say the server config, then your server won't hot reload.
UniversalHotReload({ serverConfig, clientConfig });

Advanced

If you use the serverHotReload function then you won't need to supply your own server webpack config. universal-hot-reload uses a default server webpack config so you don't have to supply your own.

If you want to use your own custom server webpack config or if you want to hot reload your universal app, then you'll need to supply your own webpack configs. Follow the lines marked Important.

  1. Your server webpack config should look like this:

    const path = require('path');
    const nodeExternals = require('webpack-node-externals');
    
    module.exports = {
      mode: 'development',
      devtool: 'source-map',
      entry: './src/server/server.js',
      target: 'node', // Important
      externals: [nodeExternals()], // Important
      output: {
        path: path.resolve('dist'),
        filename: 'serverBundle.js',
        libraryTarget: 'commonjs2' // Important
      },
      // other webpack config
    };
  2. Your client webpack config should look like this:

    const path = require('path');
    const webpackServeUrl = 'http://localhost:3002';
    
    module.exports = {
      mode: 'development',
      devtool: 'source-map',
      entry: './src/client/index',
      output: {
        path: path.resolve('dist'),
        publicPath: `${webpackServeUrl}/dist/`, // Important: must be full path with trailing slash
        filename: 'bundle.js'
      },
      // other webpack config
    };
  3. Create an index.js file:

    const UniversalHotReload = require('universal-hot-reload').default;
    
    // You can provide only a server or a client config or both. 
    const serverConfig = require('../webpack.config.server.js');
    const clientConfig = require('../webpack.config.client.js');
    
    // Omitting a config means that side of your app won't hot reload.
    UniversalHotReload({ serverConfig, clientConfig });
  4. Lastly in your server entry file:

    import { getDevServerBundleUrl } from 'universal-hot-reload';
    import webpackClientConfig from 'path/to/webpack.config.client';
    
    // Important: gets webpack-dev-server url from your client config 
    const devServerBundleUrl = getDevServerBundleUrl(webpackClientConfig);
    
    // Important: feed the url into script src
    const html = `<!DOCTYPE html>
                <html>
                  <body>
                    <div id="reactDiv">${reactString}</div>
                    <script src="${devServerBundleUrl}"></script>
                  </body>
                </html>`;
                
    // Important: the listen method returns a http.server object which must be default exported
    // so universal-hot-reload can access it
    export default app.listen(PORT, () => {
      log.info(`Listening at ${PORT}`);
    });
  5. Run your app!

    node index.js

Examples

For graphql, check this example with nexus, apollo server and typescript. Only express-graphql and apollo-server are supported right now. graphql-yoga does not expose its http.server instance and so it's not hot-reloadable this way for now.

For universal webpack apps, check the react example for a fully working spa with react and react-router.

universal-hot-reload's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

universal-hot-reload's Issues

Doesn't work with multiple Entry Points

I added a named entry point to the webpack.config.client and it wouldn't work. Any ideas?

webpack.config.client.js

module.exports = {
  entry: {
    client: [
      'webpack-dev-server/client?' + webpackDevServerUrl,
      'webpack/hot/only-dev-server',
      './src/client/index'
    ]
  },
  ...
}

Error Message:

universal-hot-reload/lib/getDevServerPort.js:22
var devServerEntry = clientConfig.entry.find(function (entry) {
^
TypeError: clientConfig.entry.find is not a function

Didn't work on windows (PR ready)

Hi Yusinto, ty for the awesome package!

I have found a problem in your package in windows enviroment. The problem is here.

You are concatenating the output path with the file name with "/" the is the right separator in Linux and MAC but didn't work in windows. Thae first compilation work fine but when i change a file the server stop and didn't start anymore. The problem is that the require cache save it with the right slash (Node.js fix this slash inconsistency before save the result in the cache). When you tro to clean the cache in the "clearRequireCache.js" file you are clearing the wrong path (before the Node.js fix).

The core Node.js module "path" contains the "sep" variable that work right in all OS. Or you can use "resolve" function to fix the problem (always in the "path" module).

I can do the PR if you want.

Thank you for your work!

universalHotReload is not a function

Hi! I wanted to point out that the import of the universal-hot-reload module in server/index.js has to be made like this:
require('universal-hot-reload').default;

Had a bit of a headache figuring this out. Update the documentation and keep up the good work!

Old dependencies and deprecated modules

Thanks for sharing this great app. I've been looking for a decent setup to develop Front end with SSR and this is the best I've found.

I would like to use this for a new project but there are a number of issues related to old dependencies:

  • It doesn't work with Node 10.13.0 (current LTS).
  • Babel still uses old beta modules.
  • webpack-serve was deprecated and webpack-dev-sever should be used instead.

These are the latest versions of all modules (and they work with Node 10 but there's a problem with webpack-serve related to a breaking change in the last version):

"dependencies": {
    "webpack": "^4.25.1",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.10",
    "webpack-node-externals": "^1.7.2",
    "webpack-serve": "^2.0.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.1.5",
    "@babel/core": "^7.1.6",
    "@babel/node": "^7.0.0",
    "@babel/preset-env": "^7.1.6",
    "@babel/preset-react": "^7.0.0",
    "babel-core": "^7.0.0-0",
    "babel-eslint": "^10.0.1",
    "babel-jest": "^23.6.0",
    "babel-loader": "^8.0.4",
    "eslint": "^5.9.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-friendly-formatter": "^4.0.0",
    "eslint-plugin-babel": "^5.2.1",
    "eslint-plugin-import": "^2.9.0",
    "eslint-plugin-jsx-a11y": "^6.0.3",
    "eslint-plugin-react": "^7.7.0",
    "jest": "^23.6.0",
    "rimraf": "^2.6.2",
    "testdouble": "^3.6.0"
  }

FYI the easiest way to upgrade all the modules is to set all versions to "0.0.0" and then run npx npm-check-updates and then npm install again. Do you think you will update this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.