【Issues-Webpack-N1】extract-text-webpack-plugin使用css-loader报错
错误描述:
Module build failed: ModuleBuildError: Module build failed: TypeError: Cannot read property 'postcss' of null
目的:将 css 都打包到同一个指定文件当中,出现如上报错
代码:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var cssLoader = [
'style-loader',
{
loader: 'css-loader',
options: {
// modules: true, // 为true会将类名打包成hash值
importLoaders: 1 // 前面有几个loader 值就是多少
}
},
{
// 使用postcss时候必须要有选项,并且选项中必须有内容
// 否则会报错:No Postcss config found.
// 具体配置和选项参考:https://github.com/michael-ciniawsky/postcss-load-config
loader: 'postcss-loader',
// 配置也可以通过 postcss.config.js 指定
options: {
plugins: (loader) => [
require('autoprefixer')()
]
}
}
];
module.exports = { // css loader
test: /\.css$/,
use: ExtractTextPlugin.extract(cssLoader)
// use: ExtractTextPlugin.extract({
// fallback: 'style-loader',
// use: 'css-loader'
// })
};
如果使用 cssLoader 就会报错,说无法读取 ‘postcss’,如果换成如下:
module.exports = { // css loader
test: /\.css$/,
// use: ExtractTextPlugin.extract(cssLoader)
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
};
就能正常使用,但是这样就没法使用 postcss
了,并且没法配置更多的选项。
通过排除法,终于找出了导致失败的的地方,但不知为何会有影响
参考地址:ExtracCSS-Fail-Issue
解决方法:
去掉 cssLoader 里面的 style-loader,添加 fallback: 'style-loader'
最后 cssLoader.js
的代码完整如下:
/*
css loader
*/
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var cssLoader = [
// 'style-loader',
{
loader: 'css-loader',
options: {
// modules: true, // 为true会将类名打包成hash值
importLoaders: 1 // 前面有几个loader 值就是多少
}
},
{
// 使用postcss时候必须要有选项,并且选项中必须有内容
// 否则会报错:No Postcss config found.
// 具体配置和选项参考:https://github.com/michael-ciniawsky/postcss-load-config
loader: 'postcss-loader',
// 配置也可以通过 postcss.config.js 指定
options: {
plugins: (loader) => [
require('autoprefixer')()
]
}
}
];
module.exports = { // css loader
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssLoader
})
};
可实现功能:
- 将
*.css
文件内的样式打包到一个文件内 - 自动添加前缀