日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

样式处理——提取样式文件

發布時間:2025/7/14 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 样式处理——提取样式文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前提說明

提取樣式文件就是把源代碼中寫的樣式提取成一個單獨的文件,不是讓其在 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

總結

以上是生活随笔為你收集整理的样式处理——提取样式文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。