Webpack 使用 ExtractTextPlugin 搭配 autoprefixer 的疑问

#1

我们的项目当中遇到这样的需求:

开发环境, 要使用纯 CSS 代码, 通过 HTML link 标签加载
部署环境, 要用 autoprefixer 处理过的 CSS, 并且用 ExtractTextPlugin 分离出 CSS 文件

这样的目的, 开发时使用 Chrome Workspace 调试, 部署的时候 CSS 可以独立加载
因为 HTML 可以是服务端渲染的, 所以 CSS 独立加载呆着页面渲染更好一些

折腾了半天, ExtractTextPlugin 总是有问题, 不过后来很奇怪还是搞定了
http://ui.talk.ai/coffee-webpack-starter/

是这样一串代码:

      {test: /\.less$/, loader: 'style!css!less'}
      {test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css!autoprefixer')}

完整的配置在 GitHub 上可以看到:
https://github.com/teambition/coffee-webpack-starter/blob/master/webpack.config.coffee#L25

问题是, ExtractTextPlugin 插件的运行原理是怎么, 几个参数我稍微改一下就好保存,
也不清楚报错的时候, 原因是什么?

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("!");
	}
};

https://github.com/webpack/extract-text-webpack-plugin/blob/master/index.js

有没有了解 loader 加载机制同学知道这中间的细节?

1 Like
#2

具体是啥错呢?还是说这份配置是有出错的配置?

#3

现在的配置是对的, 不过是照以前的一份配置凑出来的:

      {test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css!autoprefixer')}

问题是 ExtractTextPlugin.extract 如果不是这样写, 比如写成 style!css!autoprefixer 那就会报错.
报错的代码是 autoprefixer 里边的…

我弄不清楚这个参数具体是怎么起作用的, 还有不这样写为什么报错

#4

就extract签名来说,两种用法肯定有区别的。细节明天再看看

#5
ExtractTextPlugin.extract([notExtractLoader], loader, [options])

noExtractLoader可选参数,未提取的css会被这个loader处理。你合并起来成为style!css!autoprefixer的话,也就是loader等于style!css!autoprefixer,ExtractTextPlugin.extract会在这个loader列表前插入一个loader,并且最后会执行style-loader所返回的module,这时style-loader就会报错了,提示style-loader返回的module只能在浏览器环境中执行。

不过extract-text-plugin所带的loader真没太看懂,比较复杂。

还有有几个概念不是很清楚,这几个Chunk type

2 Likes