1.css文件编译 webpack默认只能编译js文件,引入css需要loader支持 // css文件写入js中 npm i style-loader -D // css文件loader npm i css-loader -D webpack.config.js的rules中添加 { test: /\.css$/, use:[‘style-loader‘, ‘css-loader‘] } 2.css自动添加前缀 // postcss-loader 可以给css自动添加-webkit -ms前缀 npm i postcss-loader -D //autoprefixer插件,针对浏览器兼容设置 npm i autoprefixer -D // 增加postcss-loader的option 新增文件postcss.config.js,内容: module.exports = { plugins: { autoprefixer: { browsers: [‘last 7 iOS versions‘, ‘last 3 versions‘, ‘> 1%‘] } } } 3.css剥离 //安装剥离插件(如果你是全局webpack,使用时会要你安装到当前项目) npm i mini-css-extract-plugin -D webpack.config.js中引入并使用 //引入 const MiniCssExtractPlugin = require("mini-css-extract-plugin"); //添加到plugins数组中 plugins:[ new MiniCssExtractPlugin({ filename: "css/main.css", }) ] //在rules中写入处理loader(之前的style-loader拿掉,因为不需要写入js文件了) rules:[ { test: /\.css$/, use:[MiniCssExtractPlugin.loader, ‘css-loader‘, ‘postcss-loader‘] } ]
package.json文件:
{ "name": "csschange", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack --config webpack.config.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "autoprefixer": "^9.6.1", "css-loader": "^3.2.0", "mini-css-extract-plugin": "^0.8.0", "postcss-loader": "^3.0.0", "style-loader": "^1.0.0", "webpack": "^4.41.0", "webpack-cli": "^3.3.9" } }
webpack.config.js文件:
const path = require(‘path‘) const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { entry:‘./main.js‘, output:{ filename:‘bundle.js‘, path:path.resolve(__dirname,‘./dist‘) }, module:{ rules:[ { test: /\.css$/, use:[MiniCssExtractPlugin.loader, ‘css-loader‘, ‘postcss-loader‘] } ] }, plugins:[ new MiniCssExtractPlugin({ filename: "css/main.css", }) ] }
postcss.config.js文件:
module.exports = { plugins: { autoprefixer: { browsers: [‘last 7 iOS versions‘, ‘last 3 versions‘, ‘> 1%‘] } } }
原文地址:https://www.cnblogs.com/superjsman/p/11599662.html
时间: 2024-10-07 12:16:38