Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack - ReferenceError: document is not defined

tl;dr: Webpack won't compile and I'm not sure why when everything looks syntactically correct, and also I don't fully understand what this error is implying.

Trying to use webpack. Full disclosure: really new to this (js/front end in general). I finally resolved the other errors I was getting (mostly just pointing to wrong filepaths or syntax errors). I followed a youtube video to get this set up , which in hindsight might not have been the best idea, but I needed to begin somewhere and watching is easier than reading. Anyway so I followed that and got things moving. Installed everything with npm (see package.json below) and created the src/dist and so forth. I am not using React/Angular/Vue etc, just regular plain old vanilla javascript. And I'm on Linux, if that makes any bit of difference (I'd imagine not).

Then I was met with this error:

ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /home/alan/dev/privateFolder/shrektime
ℹ 「wdm」: wait until bundle finished: /
✖ 「wdm」: Hash: 91bf4b6307b254c69adc
Version: webpack 4.44.1
Time: 1110ms
Built at: 04/09/2020 04:20:38
                               Asset      Size  Chunks                         Chunk Names
                    .dist/index.html  1.39 KiB          [emitted]              
55e664c36a02d03a083764a7c577f012.png  17.2 KiB          [emitted] [immutable]  
                           bundle.js   374 KiB    main  [emitted]              main
Entrypoint main = bundle.js
[0] multi (webpack)-dev-server/client?http://localhost:8080 ./src/main.js 40 bytes {main} [built]
[./node_modules/strip-ansi/index.js] 161 bytes {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.91 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js] (webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js] (webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./src/js/components/Calendar.js] 1.18 KiB {main} [built]
[./src/js/components/Input.js] 171 bytes {main} [built]
[./src/js/components/Results.js] 603 bytes {main} [built]
[./src/js/handlers/base.js] 356 bytes {main} [built]
[./src/main.js] 2.7 KiB {main} [built]
    + 23 hidden modules

ERROR in   Error: /home/alan/dev/privateFolder/shrektime/node_modules/style-loader/dist/runtime/injectStylesIntoSty  leTag.js?:93
    var style = document.createElement('style');
                ^
  ReferenceError: document is not defined
  
  - injectStylesIntoStyleTag.js?:93 insertStyleElement
    [.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:93:15
  
  - injectStylesIntoStyleTag.js?:208 addStyle
    [.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:208:13
  
  - injectStylesIntoStyleTag.js?:81 modulesToDom
    [.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:81:18
  
  - injectStylesIntoStyleTag.js?:239 module.exports
    [.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:239:25
  
  - style.css?:15 eval
    /home/alan/dev/privateFolder/shrektime/src/style.css?:15:14
  
  - index.html:240 Object../src/style.css
    /home/alan/dev/privateFolder/shrektime/src/index.html:240:1
  
  - index.html:21 __webpack_require__
    /home/alan/dev/privateFolder/shrektime/src/index.html:21:30
  
  - loader.js:3 eval
    [index.html?.]/[html-webpack-plugin]/lib/loader.js:3:34
  
  - index.html:133 Object../node_modules/html-webpack-plugin/lib/loader.js!./src    /index.html
    /home/alan/dev/privateFolder/shrektime/src/index.html:133:1
  
  - index.html:21 __webpack_require__
    /home/alan/dev/privateFolder/shrektime/src/index.html:21:30
  

Child HtmlWebpackCompiler:
                                   Asset      Size  Chunks                         Chunk Names
    55e664c36a02d03a083764a7c577f012.png  17.2 KiB          [emitted] [immutable]  
     + 1 hidden asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/css-loader/dist/cjs.js!./src/style.css] 5.29 KiB {HtmlWebpackPlugin_0} [built]
    [./node_modules/css-loader/dist/runtime/api.js] 2.46 KiB {HtmlWebpackPlugin_0} [built]
    [./node_modules/html-loader/dist/runtime/getUrl.js] 548 bytes {HtmlWebpackPlugin_0} [built]
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 4.34 KiB {HtmlWebpackPlugin_0} [built]
    [./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js] 6.64 KiB {HtmlWebpackPlugin_0} [built]
    [./src/img/icons8-shrek-256.png] 80 bytes {HtmlWebpackPlugin_0} [built]
    [./src/js/components/Calendar.js] 1.18 KiB {HtmlWebpackPlugin_0} [built]
    [./src/js/components/Input.js] 171 bytes {HtmlWebpackPlugin_0} [built]
    [./src/js/components/Results.js] 603 bytes {HtmlWebpackPlugin_0} [built]
    [./src/js/handlers/base.js] 356 bytes {HtmlWebpackPlugin_0} [built]
    [./src/js/handlers/dateHandler.js] 1.97 KiB {HtmlWebpackPlugin_0} [built]
    [./src/main.js] 2.7 KiB {HtmlWebpackPlugin_0} [built]
    [./src/style.css] 519 bytes {HtmlWebpackPlugin_0} [built]
ℹ 「wdm」: Failed to compile.

here is my package.json

{
  "name": "shrektime",
  "version": "1.0.0",
  "description": "A stupid idea gone too far",
  "main": "main.js",
  "type": "module",
  "dependencies": {
    "fractional": "^1.0.0",
    "lodash": "^4.17.20",
    "moment": "^2.27.0"
  },
  "devDependencies": {
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "babel-loader": "^8.1.0",
    "css-loader": "^4.2.2",
    "file-loader": "^6.1.0",
    "html-loader": "^1.3.0",
    "html-webpack-plugin": "^4.4.1",
    "mini-css-extract-plugin": "^0.11.0",
    "node-sass": "^4.14.1",
    "sass-loader": "^10.0.2",
    "style-loader": "^1.2.1",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  },
  "scripts": {
    "compile:sass": "node-sass src/sass/main.scss src/style.css -w",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --mode-development --open"
  },
  "author": "Alan Nardo",
  "license": "ISC"
}

in my main.js folder I have the CSS and Sass imported as such:

import sass from './sass/main.scss';
import css from './style.css';

and finally my webpack.config.js file:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');

module.exports = {

    entry: "./src/main.js",
    output: {
        filename: 'bundle.js',
        path: path.join(__dirname, 'dist'),
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: { loader: "babel-loader" }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                ]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    { loader: "file-loader" }
                ]
            },
            {
                test: /\.css$/,
                use: [
                    "style-loader",
                    "css-loader"
                ],
            },
            {
                test: /\.scss$/,
                loaders: ['style-loader', 'css-loader', 'sass-loader']
            },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html",
            filename: ".dist/index.html"
        }),
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        })
    ]
};

This is an image of my folder structure:

project structure

like image 246
nos codemos Avatar asked Sep 04 '20 11:09

nos codemos


2 Answers

I just had, and solved this issue, without finding an answer on stackoverflow. So here how I caused this problem: In webpack, in your loader section, if you leave out the 'test' part of your rule, you may trigger this error. The issue is, that webpack will invoke your loader on the wrong kinds of files, and give errors like this.

..
module: { 
  rules: [
    { 
      test: /\.ts$/, 
      use: 'ts-loader', exclude: /node_modules/ 
    },
  ] 
}
..

(I'm aware the above question contains tests, but my reputation is too low to comment, and I believe understanding the underlying causes of the error is relevant to figuring out how to solve them. I don't like unexplained 'I did thing and now it works!! kinds of answers.)

like image 167
jakob gaardsted Avatar answered Oct 19 '22 20:10

jakob gaardsted


So I'm not sure if anyone else will have quite the same error, but just in case, there's nothing worse than searching forums and finding the exact same error and nobody leaving an answer.

I got help from a friendly redditor (shoutout r/learnjavascript) and it was basically just a few syntax errors here and there and me not understanding how things work.

under the HtmlWebpackPlugin I had to change the filename from .dist/index.html to index.html and had to add in the following code in the module.exports of webpack.config.js for the webpack-dev-server to run:

    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 9000
    }

which is pulled right from the docs page https://webpack.js.org/configuration/dev-server/#devserver. Presumably you can choose any port number you fancy.

Additionally, I had to change how I imported one of my js files as it is a class (and tbh I should probably change that but I'll cross that bridge when I get to it). It's called Calendar.js so instead of doing import * as Calendar from './Calendar' I had to use import Calendar from './Calendar'.

Finally, in my src/index.html I left in the style and script tags for the css and main.js respectively, so I had to remove those.

like image 2
nos codemos Avatar answered Oct 19 '22 18:10

nos codemos