在 webpack 中使用 style-loader 时出现“窗口未定义"错误 [英] 'window is not defined' error when using style-loader with webpack

查看:58
本文介绍了在 webpack 中使用 style-loader 时出现“窗口未定义"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构建服务器端 React 应用程序,在使用 Webpack 时,我遇到了 Style-Loader 问题.

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

我使用的是^0.23.1"版本,当运行脚本来捆绑和构建时,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.

问题是窗口未定义

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

有人遇到过这个问题吗?在查看了堆栈和样式加载器的 Github 问题后,我没有找到任何解决方案.

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

这是我的 webpack 文件:

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.

推荐答案

style-loader 尝试将样式注入网站的 head (window/document),在您的服务器上呈现/执行时将不存在.

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.

你需要从你的服务器配置中删除这个加载器并用其他东西替换它(例如 ExtractTextPluginMiniCSSExtractplugin,取决于你的 webpack版本)

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)

这篇关于在 webpack 中使用 style-loader 时出现“窗口未定义"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆