将css从js中提取出来
webpack编译打包时,css是被放在 js 中的,通过 style 标签加载到页面上,通过将 css 从 js中提取出来,可以使用 link 方式加载 css
用到一个插件 , mini-css-extract-plugin
首先下载这个插件 npm install --save-dev mini-css-extract-plugin
src / index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>webpack</title> </head> <body> <div id="box1"></div> <div id="box2"></div> </body> </html>
src / index.js
import './css/a.css' import './css/b.css'
webpack.config.js
const {resolve} = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:resolve(__dirname,'build') }, module:{ rules:[ { test:/\.css$/, use:[ MiniCssExtractPlugin.loader, //这个loader取代style-loader,将css从js中提取出来 'css-loader' ] } ] }, plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html' }), new MiniCssExtractPlugin({ filename:'bundle.css' //对输出的css文件进行重命名 }) ], mode:'development' }
npx webpack 执行后,生成一个 bundle.css 文件(进行了重命名,默认是 main.css)
build / bundle.css
#box1{ width:100px; height:100px; background-color: red; } #box2{ width:100px; height:100px; background-color: blue; }
build / index.html 生成的 html 中自动通过 link 方式引入样式文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>webpack</title> <link href="bundle.css" rel="stylesheet"></head> <body> <div id="box1"></div> <div id="box2"></div> <script src="bundle.js"></script></body> </html>