使用extract-text-webpack-plugin React时,窗口未定义错误
我正在使用webpack来构build我的反应组件,我试图使用extract-text-webpack-plugin来从我生成的js文件中分离出我的css。 但是,当我尝试构build组件时出现以下错误: 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') ] } 
	
 您可能希望在extract函数中将style-loader用作before参数。 
这是本地实现:
  ExtractTextPlugin.extract = function(before, loader, options) { if(typeof loader === "string") { return [ ExtractTextPlugin.loader(mergeOptions({omit: before.split("!").length, extract: true, remove: true}, options)), before, loader ].join("!"); } else { options = loader; loader = before; return [ ExtractTextPlugin.loader(mergeOptions({remove: true}, options)), loader ].join("!"); } }; 
所以基本上你需要做的是:
 { test: /\.sass$/, exclude: /node_modules/, loader: ExtractTextPlugin.extract('style-loader', 'css!sass?indentedSyntax=true&sourceMap=true') }, 
 如果你例如使用sass 。 
没有看到原因的解释,所以我已经在这里发布了这个答案。
从https://github.com/webpack/extract-text-webpack-plugin#api
ExtractTextPlugin.extract([notExtractLoader], loader, [options])从现有的装载器创build一个解压缩装载器。
notExtractLoader(可选)当css未被提取时应该使用的加载器(即,当allChunk:false时,在一个>附加块中)
loader应该用于将资源转换为css导出模块的加载程序。
options
publicPath覆盖此加载器的publicPath设置。
  #extract方法应该会收到一个输出css的加载器。 发生了什么事是它正在接收一个style-loader输出JavaScript代码 ,这是打算注入到一个网页。 这段代码会尝试访问window 。 
 你不应该把style的loaderstring传递给#extract 。 但是…如果你设置allChunks=false ,那么它不会为非初始块build立CSS文件。 因此它需要知道用什么加载器来注入页面。 
提示:Webpack是一个真正需要深入理解的工具,或者可能遇到许多奇怪的问题。
Webpack 2
如果你使用的是Webpack 2,这种变化的工作原理是:
  rules: [{ test: /\.css$/, exclude: '/node_modules/', use: ExtractTextPlugin.extract({ fallback: [{ loader: 'style-loader', }], use: [{ loader: 'css-loader', options: { modules: true, localIdentName: '[name]__[local]--[hash:base64:5]', }, }, { loader: 'postcss-loader', }], }), }] 
新的提取方法不再需要三个参数,当从V1移动到V2时,被列为突变。
https://webpack.js.org/guides/migrating/#extracttextwebpackplugin-breaking-change
我想出了解决我的问题的方法:
  (而不是将这些装载器相互连接起来( ExtractTextPlugin.extract('style-loader!css-loader') ),你必须把每个装载器作为一个单独的参数ExtractTextWebpackPlugin.extract('style-loader', 'css-loader') : ExtractTextWebpackPlugin.extract('style-loader', 'css-loader')