样式处理——预处理器stylus

前提说明

为了写样式方便快速,现在很多时候写样式都是使用预处理器了,预处理器有很多,包括 Sass、Less、Stylus 等。在这里选用的预处理器是 Stylus。

需要用到的模块:

  • stylus
  • stylus-loader

文件的后缀名:.styl

准备工作

首先,还是把需要的依赖安装一下 package.json

  "scripts": {
    "webpack": "webpack"
  },
  "devDependencies": {
    "css-loader": "^1.0.0",
    "mini-css-extract-plugin": "^0.4.2",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.2",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0"
  }

其次,就是准备 Webpack 的配置文件 webpack.config.js,当然,这个配置文件是一部分:

const { join, relative } = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

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.plugins = [new MiniCssExtractPlugin({
  filename: "[name].css"
})];
config.module = {
  rules: []
};

module.exports = config;

最后,就是准备一下需要的代码文件:

index.js

import './css/common.styl';

css/common.styl

* {
  margin: 0;
  padding: 0;
}

.my-div {
  width: 100%;
  height: 120px;
  background-color: aqua;
}

span {
  font-size: 16px;
}

配置 stylus-loader

config.module.rules.push({
  test: /\.styl$/,
  use: [
    {
      loader: MiniCssExtractPlugin.loader
    },
    {
      loader: 'css-loader'
    },
    {
      loader: 'stylus-loader'
    }
  ]
});

执行命令 yarn webpack 之后,在 dist 目录下面就会出现一个 index.css 文件,这个样式文件就是通过 stylus-loader 转换生成的样式文件。

猜你喜欢

转载自www.cnblogs.com/negivup/p/9558862.html