PostCSS 和自动添加前缀 (postcss-loader) 与 Webpack Encore
PostCSS 是一个 CSS 后处理工具,可以通过许多很酷的方式转换你的 CSS,例如 自动添加前缀、代码检查等等!
首先在 webpack.config.js
中启用它
1 2 3 4 5 6
// webpack.config.js
Encore
// ...
+ .enablePostCssLoader()
;
然后重启 Encore。 当你这样做时,它会给你一个命令,你可以运行该命令来安装任何缺少的依赖项。 运行该命令并重启 Encore 后,就完成了!
接下来,下载任何你想要的插件,例如 autoprefixer
1
$ npm install autoprefixer --save-dev
接下来,在你的项目根目录下创建一个 postcss.config.js
文件
1 2 3 4 5 6 7 8 9
module.exports = {
plugins: {
// include whatever plugins you want
// but make sure you install these via npm!
// add browserslist config to package.json (see below)
autoprefixer: {}
}
}
就是这样! postcss-loader
现在将用于所有 CSS、Sass 等文件。 你也可以通过传递回调来将选项传递给 postcss-loader
1 2 3 4 5 6 7 8 9 10 11 12
// webpack.config.js
+ const path = require('path');
Encore
// ...
+ .enablePostCssLoader((options) => {
+ options.postcssOptions = {
+ // the directory where the postcss.config.js file is stored
+ config: path.resolve(__dirname, 'sub-dir', 'custom.config.js'),
+ };
+ })
;
在 package.json
中添加 browserslist
autoprefixer
(和许多其他工具) 需要知道你想支持哪些浏览器。 最佳实践是直接在你的 package.json
中配置它 (以便所有工具都可以读取它)
1 2 3 4 5
{
+ "browserslist": [
+ "defaults"
+ ]
}
对于大多数用户,推荐使用 defaults
选项,它相当于以下 browserslist
1 2 3 4 5 6 7 8
{
+ "browserslist": [
+ "> 0.5%",
+ "last 2 versions",
+ "Firefox ESR",
+ "not dead"
+ ]
}
有关语法的更多详细信息,请参阅 browserslist。
这项工作,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可协议获得许可。