• webpack4从0开始构建前端单页项目(9)用less-loader处理css


    安装 less less-loader

        cnpm i less less-loader -D
    

    项目结构

        project
        |   .babelrc            # babel-loader配置文件
        |   .editorconfig       # 配置格式化插件
        |   package.json        # 项目需要的依赖
        |   webpack.config.js   # webpack配置文件
        |
        +---public
        |       index.html      # 用于打包生成 .html 文件的模板
        |
        ---src
                main.js         # webpack的入口文件
                style.less       # less文件
    

    在 main.js 中引入.less 文件

    \ main.js
        import "./style.less";
    

    依赖的模块(package.json)

        "devDependencies": {
            "@babel/core": "^7.11.6",
            "@babel/preset-env": "^7.11.5",
            "babel-loader": "^8.1.0",
            "css-loader": "^4.3.0",
            "html-webpack-plugin": "^4.5.0",
            "less": "^3.12.2",
            "less-loader": "^7.0.1",
            "style-loader": "^1.2.1",
            "webpack": "^4.44.2",
            "webpack-cli": "^3.3.12",
            "webpack-dev-server": "^3.11.0"
        }
    

    webpack 配置文件

    // webpack.config.js
        const webpack = require("webpack");
        const path = require("path");
        const htmlWebpackPlugin = require("html-webpack-plugin");
    
        module.exports = {
            entry: "./src/main.js",
            mode: "development",
            output: {
                path: path.join(__dirname, "dist"),
                filename: "app.[hash:16].js",
            },
            plugins: [
                new htmlWebpackPlugin({
                    filename: "index.html",
                    template: "./public/index.html",
                    minify: {
                        collapseWhitespace: false,
                    },
                    inject: true,
                }),
            ],
            devServer: {
                contentBase: path.join(__dirname, "dist"),
                compress: true,
                port: 9000, // 配置端口
                hot: true,
            },
    
            module: {
                rules: [
                    {
                        test: /.js$/,
                        exclude: /(node_modules|bower_components)/,
                        use: "babel-loader",
                    },
                    {
                        test: /.less$/,
                        use: ["style-loader", "css-loader", { loader: "less-loader" }],
                    },
                ],
            },
        };
    

    less-loader一定要放在loader最后。

    less-loader 参考: https://webpack.docschina.org/loaders/less-loader/

    开发工具
  • 相关阅读:
    JavaScript优美的特性
    指尖初体验之主屏幕操作
    XHTML下css+div布局总结
    CSS表常用小技巧
    让两个DIV居中显示
    用CSS做滑动门
    CSS控制文本自动换行
    符合css规范的下拉菜单(兼容ff\ie6\ie7)
    层垂直居中于浏览器
    用css来强制按比例压缩图片的高度或宽度
  • 原文地址:https://www.cnblogs.com/cisbest/p/13757393.html
Copyright © 2020-2023  润新知