karrar's avatar

High CPU Usage when running npm run watch

I have an application that is built with Vue 2 and Inertia. When I run npm run watch, I notice that the CPU usage spikes up to 99% and then goes down. Is this normal behavior, or is there something that I might be missing?

package.json :

"private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },

webpack.mix.js

const mix = require("laravel-mix");
const webpackConfig = require('./webpack.config')

if (mix.inProduction()) {
    mix.version();
}

mix.js("resources/js/app.js", "public/js").vue({version:2})
    .webpackConfig(webpackConfig)
    .sass("resources/sass/app.scss", "public/css")
    .sass("resources/sass/app-dark.scss", "public/css")
    .sass("resources/sass/app-rtl.scss", "public/css")
    .options({
        processCssUrls: false
    }).version();

webpack.config.js:

const path = require('path')
module.exports = {
    output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
    resolve: {
        alias: {
            '@': path.resolve('./resources/js'),
        },
        extensions: ['.js', '.vue', '.json'],
    },
    devServer: {
        allowedHosts: 'all',
    },
}

0 likes
1 reply
LaryAI's avatar
Level 58

It is normal for the CPU usage to spike up when running npm run watch as it is constantly watching for changes in the files. However, there are a few things that can be done to reduce the CPU usage:

  1. Increase the polling interval by running npm run watch-poll instead of npm run watch. This will reduce the number of times the file system is checked for changes.

  2. Exclude unnecessary files and directories from being watched by adding them to the webpack.mix.js file. For example, if there are large files or directories that do not need to be watched, they can be excluded using the mix.disableNotifications() method.

  3. Use a more powerful CPU or upgrade the existing one.

Here is an example of how to exclude files and directories from being watched in webpack.mix.js:

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .disableNotifications()
   .webpackConfig({
       watchOptions: {
           ignored: /node_modules/
       }
   });

In this example, the node_modules directory is excluded from being watched.

Please or to participate in this conversation.