样式处理——提取样式文件
生活随笔
收集整理的这篇文章主要介绍了
样式处理——提取样式文件
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
前提说明
提取样式文件就是把源代码中写的样式提取成一个单独的文件,不是让其在 js 中加载。
提取样式文件会用到一个模块 mini-css-extract-plugin,这个模块是 loader 和 plugin 结合使用的。
准备工作
首先,还是把需要的依赖安装一下 package.json:
"scripts": {"webpack": "webpack"},"devDependencies": {"css-loader": "^1.0.0","mini-css-extract-plugin": "^0.4.2","style-loader": "^0.23.0","webpack": "^4.17.1","webpack-cli": "^3.1.0"}其次,就是准备 Webpack 的配置文件 webpack.config.js,当然,这个配置文件是一部分:
const { join, relative } = require('path');const config = {};config.mode = 'production'; config.entry = {index: join(__dirname, './src/index.js') }; config.output = {path: join(__dirname, './dist'),filename: '[name].bundle.js',chunkFilename: '[name].chunk.js',publicPath: join(__dirname, './dist/') };config.module = {rules: [] };config.plugins = [];module.exports = config;最后,就是准备一下需要的代码文件:
index.js:
import './css/common.css';function createDiv() {var element = document.createElement('div');element.className = 'my-div';element.innerHTML = '这是一个div';return element; }document.body.appendChild(createDiv());css/common.css:
* {margin: 0;padding: 0; }.my-div {width: 100%;height: 120px;background-color: aqua; }span {font-size: 16px; }配置 mini-css-extract-plugin
首先,需要在 loader 中配置 MiniCssExtractPlugin.loader,用于替换掉 style-loader。
其次,需要在 plugins 中增加相关配置:
config.module.rules.push({test: /\.css$/,use: [{loader: MiniCssExtractPlugin.loader},{loader: 'css-loader'}] });config.plugins.push(new MiniCssExtractPlugin({filename: "[name].css" }));最后执行命令 yarn webpack,在 dist 目录下就会生成一个 index.css 文件。
转载于:https://www.cnblogs.com/negivup/p/9558383.html
总结
以上是生活随笔为你收集整理的样式处理——提取样式文件的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: webpack教程(一)
- 下一篇: K8S集群tls证书管理