Webpack23配置ExtractTextPlugin和Autoprefixer

xiaoxiao2021-02-28  73

在网上搜索了三个小时,都是各种老版本的用法,完全不work,最后还是从官方文档中总结出来,赶紧分享给大家,希望更多朋友少走弯路。官方文档:https://github.com/postcss/postcss-loader

第一步,当然是安装extract-text-webpack-plugin,postcss-loader和autoprefixer了。

npm install extract-text-webpack-plugin postcss-loader autoprefixer --save

第二步,新建一个文件取名postcss.config.js,添加如下代码,也就是兼容最新的5个浏览器版本。

module.exports = { plugins: { 'autoprefixer': {browsers: 'last 5 version'} } }

第三步,在webpack.config.js开头加入如下引用

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

第四步,在webpack.config.js中的module加入loader,见下方代码的最后一条,添加了对scss,sass,css的解析,有一点需要注意,根据官方文档中的描述,postcss-loader需要在style-loader和css-loader之后,其他loader(比如sass-loader)之前。

module: { loaders: [{ // babel loader test: /\.js?$/, exclude: /node_modules/, loader: "babel-loader" }, { test: /\.(png|jpg|jpng)$/, // pack images loader: 'url-loader?limit=8192&name=resource/image/[name]-[hash:8].[ext]' }, { test: /\.(woff|woff2|eot|ttf|svg)(\?[a-z0-9]+)?$/, loader: 'url-loader?limit=1000&name=resource/fonts/[name]-[hash:8].[ext]' }, { test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery', // jQuery and $ }, { test: /\.ejs$/, loader: 'ejs-loader', }, { test: /\.(scss|sass|css)$/, // pack sass and css files loader: ExtractTextPlugin.extract({fallback: "style-loader", use: "css-loader!postcss-loader!sass-loader"}) } ] }

第五步,在webpack.config.js中的plugins加入打包后的css文件名,这里取名为index.css。

plugins: [ new HtmlWebpackPlugin({ template: 'src/index.tpl.html', inject: 'body', filename: 'index.html' }), new webpack.optimize.CommonsChunkPlugin("vendor.bundle.js"), //packed independently such as react and react-dom new ExtractTextPlugin("index.css"), // pack all the sass and css files into index.csss new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development') }) ]

完成以上五步之后,亲测对”webpack”: “^3.1.0”管用。有什么疑问可以在下方或者我的微博中留言。

转载请注明原文地址: https://www.6miu.com/read-46399.html

最新回复(0)