使用extract-text-webpack-plugin React时未定义窗口错误

reactjs React.js

卡卡西西里

2020-03-13

我正在使用webpack构建我的react组件,并且试图使用extract-text-webpack-plugin来将css与生成的js文件分开。但是,当我尝试构建组件时,出现以下错误: Module build failed: ReferenceError: window is not defined

我的webpack.config.js文件如下所示:

var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
    MainComponent: './src/main.js'
  },
  output: {
    libraryTarget: 'var',
    library: 'MainComponent',
    path: './build',
    filename: '[name].js'
  },
  module: {
    loaders: [{
      test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader!css-loader')
    }]
  },
  plugins: [
    new ExtractTextPlugin('styles.css')
  ]
}

第1388篇《使用extract-text-webpack-plugin React时未定义窗口错误》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Tom西里 2020.03.13

没有找到原因的解释,所以我在这里发布了此答案。

来自https://github.com/webpack/extract-text-webpack-plugin#api

ExtractTextPlugin.extract([notExtractLoader], loader, [options]) 从现有加载器创建提取加载器。

notExtractLoader (可选)未提取css时应使用的加载器(即,在allChunks:false时在>附加块中)

loader 应该用于将资源转换为CSS导出模块的加载器。

options

publicPath 覆盖此加载程序的publicPath设置。

#extract方法应接收输出的加载程序css发生的事情是,它接收到一个style-loader输出javascript代码的,该代码打算注入到网页中。此代码将尝试访问window

您不应将loader字符串传递style#extract但是...如果您设置allChunks=false,那么它将不会为非初始块构建CSS文件。因此,它需要知道要使用哪种加载器来注入页面。

提示:Webpack是真正需要深入了解的工具,否则您可能会遇到很多奇怪的问题。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android