webpack configuration (step 5: less/css (basic))

Posted by zkoneffko on Fri, 03 Apr 2020 14:22:22 +0200

Download Plug-in:

less plug-in installation

$ cnpm install less  less-loader --save-dev

By the way, the css plug-in is also installed

$ cnpm install css-loader style-loader --save-dev

webpack.config.js loaders join

,
            {
			    test: /\.less$/,
			    use: [
			        'style-loader',
			        'css-loader',
			        'less-loader' 
			    ]
			}

webpack.config.js final file:

const path = require('path');
let htmlwebpackplugin = require('html-webpack-plugin');//Introducing HTML webback plugin plug-in 
let get_html = function(name,chunk){//encapsulation
    return {
        template: './app/ejs/generate/'+ name + '.ejs',
        filename:  name+ '.html',
        chunks  : ['main',chunk||null],//Here, the common file main.js is introduced, and another file is introduced on demand. Of course, the value of this file can also be set as an array, and the second value of the incoming function can be used as an array
        chunksSortMode: 'manual',//Sort chunks in the order they were introduced
        inject  : true,//All JavaScript resources are inserted at the bottom of the body element
        hash    : true,
		xhtml	: true
    }
};

let export_html= {
    entry:  {
    	main:__dirname+"/app/js/main.js",//Entrance file
    	main1:__dirname+"/app/js/main1.js",//Entrance file
    },
    output: {
        path: __dirname+"/_build/",
        filename: "js/[name].js",//Output file. The name is determined according to the entry file key name of the entry
    },
    module: {
        loaders: [
			{
			    test: /(\.jsx|\.js)$/,
			    loader: 'babel-loader',
			    query: {
			      presets: ['es2015']
			    }
			}
            ,
            { 
            	test: /\.ejs$/, 
            	loader: 'ejs-loader?variable=data' 
            },
            {
			    test: /\.less$/,
			    use: [
			        'style-loader',
			        'css-loader',
			        'less-loader' 
			    ]
			}
        ]
    }
    ,
 	plugins: [
 		//new a template to test
  		new htmlwebpackplugin(get_html("home","main1"))
 	]
    
};
module.exports=export_html;	

Directory structure:

Create a new less directory in the app directory and a new style.less file in it

style.less

@f:white;
p{
    color: red;
}
p{
    a{
        color: @f;
    }
}

app/js/main.js

require("../less/style.less");

Build file:

_This line can be found in build/js/main.js


// module
exports.push([module.i, "p {\n  color: red;\n}\np a {\n  color: white;\n}\n", ""]);

It indicates that it has been compiled into css and put into the main.js generation file.

Let's use the browser to open īš build/home.html

Found that the font turned red, compiled successfully! In the next advanced chapter, we will use plug-ins to separate css generated by less

Topics: less Webpack Javascript