Prevent server restarting on some files changes

I’m just sharing this technique here. Maybe somebody will find it useful.

1. Situation

I’m using SSR (server-side-rendering) with React.
So my components have to be available for both: client and server.
So I keep them in shared folder.

2. Problem

I edit my components => server restarts.
Restart takes some time (about 5 seconds).
I dislike waiting to see the result.

3. Solution

  1. Keep components in client folder:
app/
  imports/
    client/
      components/
    server/
    shared/
  1. Create /imports/shared/components.js file:
import { Meteor } from 'meteor/meteor';

let Link;
let Layout;
let Post;

if (Meteor.isClient) {
  Link = require('/imports/client/components/Link');
  Layout = require('/imports/client/components/Layout');
  Post = require('/imports/client/components/Post');
} else {
  Link = require('/imports/server/components/Link');
  Layout = require('/imports/server/components/Layout');
  Post = require('/imports/server/components/Post');
}

export { Link };
export { Layout };
export { Post };
  1. To use components import them from this file:
import { Layout, Post } from '/imports/shared/components';
  1. Add this script to your package.json:
"script": {
  "ssr-prepare": "cd imports; rm -r server/components; cp -r client/components server/components"
}
  1. Disable imports/shared/components folder for your code editor

4. Explanation

Usually you don’t need ssr during development, so keeping components in client folder is just fine. You edit your components, client refreshes, no server restarts.

When you are ready for production (or you just want to test ssr), simply run npm run prepare-ssr. This command will copy client/components folder to server/components. Now server is able to see your components too.

shared/components.js module makes sure that client reads components from client/components and server reads them from server/components. Bad part is that you need to edit components.js file manually every time you create new component (it’s not possible to generate pathes for require dynamically). But it’s not really a big job :wink:

1 Like