Reload Express.js routes changes without manually restarting server

前端 未结 3 1411
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 18:54

I tried express-livereload, but it just reloaded view files.

Should I use another tool, or this one can be configured to watch for my index.js

相关标签:
3条回答
  • 2020-12-30 18:59

    I use express.js, normally start server by

    npm start
    

    with Nodemon installed, I use

    nodemon --exec npm start
    

    Note: nodemon app.js will NOT work here,

    because express.js use start script

    0 讨论(0)
  • 2020-12-30 19:10

    I think Nodemon has what you're looking for.

    Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development.

    Example invocation:

    nodemon index.js
    
    0 讨论(0)
  • 2020-12-30 19:15

    You can livereload both front and backend changes to the browser using 'livereload', 'connect-livereload', and 'nodemon'. Also, this way you don't need Gulp or Grunt. Here's how they work together:

    • livereload opens a high port and notifies the browser of any changed file
    • connect-livereload monkey patches every served HTML page with a JavaScript snippet that connects to this high port
    • nodemon restarts the server on any changed backend file

    Set up livereload in Express

    Set up Express to both start livereload server watching the public directory and ping the browser during nodemon-induced restart:

    const livereload = require("livereload");
    const connectLivereload = require("connect-livereload");
    
    // open livereload high port and start to watch public directory for changes
    const liveReloadServer = livereload.createServer();
    liveReloadServer.watch(path.join(__dirname, 'public'));
    
    // ping browser on Express boot, once browser has reconnected and handshaken
    liveReloadServer.server.once("connection", () => {
      setTimeout(() => {
        liveReloadServer.refresh("/");
      }, 100);
    });
    
    const app = express();
    
    // monkey patch every served HTML so they know of changes
    app.use(connectLivereload());
    

    Start Express with Nodemon

    Start the server with nodemon, for example, with a dedicated watch script by running npm run watch.

    The key point here is to ignore the public directory that's already being watched by livereload. You can also configure files with non-default extensions, like pug and mustache, to be watched.

    "scripts": {
      "start": "node ./bin/www",
      "watch": "nodemon --ext js,pug --ignore public"
    },
    

    You can read a longer explanation in "Refresh front and backend changes to browser with Express, LiveReload and Nodemon."

    0 讨论(0)
提交回复
热议问题