Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'window is not defined' error when using style-loader with webpack

Building a server side react app and while using Webpack I am having issues with Style-Loader.

I am using version "^0.23.1" and when running a script to bundle and build there is an issue from Style-Loader.

The issue is window is not defined

webpack:///./node_modules/style-loader/lib/addStyles.js?:23
    return window && document && document.all && !window.atob;

Has anyone run into this issue? After looking through Stack and the Github issues for style-loader I am not finding any solution.

Here is my webpack file:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  // webpack to use node
  target: 'node',
  entry: './src/index.js',
  output: {
    filename: 'client-build.js',
    path: path.resolve(__dirname, 'build/public'),
    publicPath: '/build/public'
  },
  module: {
    rules: [
      {
        test: /\.js$|\.jsx$/,
        loader: 'babel-loader',
        exclude: '/node_modules/',
        options: {
          presets: [
            '@babel/preset-react'
          ]
        }
      },
      {
        test: /\.(s*)css$/,
        loader: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
        test: /\.jpeg$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$|\.wav$|\.mp3$|\.jpg$|\.pdf$/,
        loader: 'file-loader',
        query: {
          name: 'assets/img/[name].[ext]'
        },
      },
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({
      "React": "react",
    }),
  ],
}

If there is anything else you need to see I can post it.

like image 589
T. Evans Avatar asked Dec 27 '18 23:12

T. Evans


2 Answers

style-loader tries to inject styles into the head of the website (window / document), which will be non-existent on your server on render / execution.

You need to remove this loader from your server-config and replace it with something else (e.g. ExtractTextPlugin or MiniCSSExtractplugin, depending on your webpack version)

like image 122
Jonathan Avatar answered Nov 07 '22 15:11

Jonathan


I think your problem is, that there is no window object when running js code on a node server. Which also makes sense, as your server has no window where your code is rendered. You can use the global object for global references instead, see this related post here: Does node.js have equivalent to window object in browser

like image 5
Jan-Luca Klees Avatar answered Nov 07 '22 16:11

Jan-Luca Klees