Getting ‘ReferenceError: document is not defined’ only when I run webpack –watch?

Solution for Getting ‘ReferenceError: document is not defined’ only when I run webpack –watch?
is Given Below:

Why would document stop being defined only when I run webpack --watch? When I run my build or dev script, compiling works great. It’s only when I try and watch. New to WP.

My end goal here is to polyfill my client-side JS and auto-reload the browser window that LiveServer opens (VSCode plugin). Right now, I’m just trying to automatically compile my code after making changes which will trigger LiveServer to reload. Is there a better approach to this?

index.js

const errors = document.querySelector('.errors');

webpack.config.js

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const NodemonPlugin = require('nodemon-webpack-plugin');

const config = {
  watch: true,
  entry: {
    rater_stater: "./src/index.js",
  },
  output: {
    filename: "index.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          MiniCssExtractPlugin.loader,
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
          "postcss-loader",
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "style.css",
      chunkFilename: "style-[id].css",
    }),
    new NodemonPlugin({
      env: {
        NODE_ENV: 'development',
      },
    })
  ],
};

module.exports = (env, argv) => {
  if (argv.mode === "development") {
    config.devtool = "source-map";
  }

  if (argv.mode === "production") {
    config.module.rules.push({
      test: /.js?$/,
      use: [
        {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      ],
      exclude: /node_modules/,
    });
  }

  return config;
};

package.json

 "scripts": {
    "build": "webpack --mode=production",
    "dev": "webpack --mode=development",
    "watch": "webpack --watch"
  },

error


ReferenceError: document is not defined
    at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180375
    at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180732
    at Object.<anonymous> (/Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180735)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

Edit:

I’m also getting this error when it does compile with webpack --mode=development. It’s like my variables are all set to null? I’m so confused. Why would this happen? I’ve tried changing it from var to let to const and still get the same error.

Other error

Code

Edit 2:

Ran a couple more tests. It’s like everything related to document is broken.. but I can console.log document. I just can’t use querySelector, etc.

Code 2

Console

All of these issues stopped when I wrapped my code with

document.addEventListener("DOMContentLoaded", function() {
     ...code
}

🤦