Fool learning web pack (5) - Extraction of css and automatic introduction of html into js/css

Keywords: Webpack React Javascript JQuery

First, based on the previous four articles, we use webpack to extract css. You need to install a plug-in here. Before installing, first of all, it should be explained that if there is no fourth article as the premise, that is, if the picture is not processed, it will not be able to parse the url in CSS when extracting css, so before extracting, it must be processed.

Then work begins. First install the extract-text-plugin plug-in. Then we modify the webpack.config.js file as follows:

var precss = require('precss');
var cssnext = require('cssnext');
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
var Ex = require('extract-text-webpack-plugin');
var webpack = require('webpack');
module.exports = {  
    //Which file is the entry file for webpack to use as the entry for the project  
    entry: {  
        index: './view/index.js',  
    },  
    //output exits let webpack place the processed files  
    output: {  
      path: __dirname+'/dist',  
      filename: '[name].js'  
    },  
    plugins:[
        // new HtmlwebpackPlugin({
        //     title: 'Hello World app'
        // }),
        new Ex('./style/[name].css')//Generate a css file
    ],
    //Always monitor file updates  
    watch: true,  
    watchOptions: {  
        ignored: /node_modules/  
    },  
    //What different modules do module modules use to process various types of files?  
    module: {  
        loaders: [  
            {  
                test: /\.jsx?$/,  
                loader: 'babel-loader',//Using babel module  
                exclude: /node_modules/,//Code that ignores mode_modules  
                query: {  
                    presets: ['es2015','react']//Parsing es6 and react languages  
                }  
            },{    
                test: /\.css?$/,    
                loaders: Ex.extract({fallback: "style-loader", use: "css-loader"})
                // loader: Ex.extract("style-loader", "css-loader"),  
                // loaders:["style-loader", "css-loader"]  
              },{  
                test: /\.(png|jpg|gif)$/,  
                loader: 'url-loader?limit=8192&name=./image/[name].[ext]?[hash]'  
              }  
        ]  
    },  
    resolve: {  
        extensions: ['.coffee','.js']  
    },  
  };  
Note that the way css loader is written, if it is written as follows, it will make an error. Maybe it is the version reason.

Ex.extract("style-loader","css-loader")

2. After installing the plug-in extracted from css, we can install html-webpack-plugin.

According to the template you set, html-webpack-plugin can generate the corresponding template file after each run. At the same time, the dependent CSS/JS will also be introduced. If the CSS/JS contains hash value, the template file generated by html-webpack-plugin will also introduce the correct version of CSS/JS file.

After installation, our webpack.config.js changes as follows:

var precss = require('precss');
var cssnext = require('cssnext');
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
var Ex = require('extract-text-webpack-plugin');
var webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {  
    //Which file is the entry file for webpack to use as the entry for the project  
    entry: {  
        index: './view/index.js',  
    },  
    //output exits let webpack place the processed files  
    output: {  
      path: __dirname+'/dist',  
      filename: '[name].[hash].js'  
    },  
    plugins:[
        new HtmlWebpackPlugin({
            title: "This is the result",
            filename: "./index.html",
            template: "./app/index.html",
            inject: "body",
            favicon: "",
            minify: {
                caseSensitive: false,//Is it case sensitive?
                collapseBooleanAttributes: true,//Is it case sensitive?
                collapseWhitespace: true//Is it case sensitive?
            },
            hash: true,
            cache: true,
            showErrors: true,
            chunks: "",
            chunksSortMode: "auto",
            excludeChunks: "",
            xhtml: false
        }),
        new Ex('./style/[name].[hash].css')//Generate a css file
    ],
    //Always monitor file updates  
    watch: true,  
    watchOptions: {  
        ignored: /node_modules/  
    },  
    //What different modules do module modules use to process various types of files?  
    module: {  
        loaders: [  
            {  
                test: /\.jsx?$/,  
                loader: 'babel-loader',//Using babel module  
                exclude: /node_modules/,//Code that ignores mode_modules  
                query: {  
                    presets: ['es2015','react']//Parsing es6 and react languages  
                }  
            },{    
                test: /\.css?$/,    
                loaders: Ex.extract({fallback: "style-loader", use: "css-loader"})
                // loader: Ex.extract("style-loader", "css-loader"),  
                // loaders:["style-loader", "css-loader"]  
              },{  
                test: /\.(png|jpg|gif)$/,  
                loader: 'url-loader?limit=8192&name=./image/[name].[ext]?[hash]'  
              }  
        ]  
    },  
    resolve: {  
        extensions: ['.coffee','.js']  
    },  
  };  

  • Title: The title of the generated HTML template will be ignored if the name of title is set in the template.

  • filename: The name of the generated template file

  • Template: template source file

  • inject: The injection location of the introduced module; the value is true/false/body/head

  • favicon: Specify the page icon;

  • minify: html-minifier integrated in html-webpack-plugin to generate template file compression configuration

  • Hash: Whether to generate hash to be added at the end of the introduction of the file address, similar to our commonly used timestamp, to avoid caching troubles

  • Cache: Does the cache need to be cached? If true is filled in, the file will be regenerated only if it changes

  • Show Errors: Whether to write error messages on the page, default true, error messages will be wrapped in a pre tag and added to the page

  • chunks: Introduced modules, where you specify when you set multiple JS in entry, where you specify the introduced js, and if you don't set them all by default.

  • chunksSortMode: The Sorting Method of Introducing Modules

  • Exclude Chunks: excluded modules

  • Xhtml: Whether the tags in the generated template document are automatically closed or not. For the syntax of xhtml, all tags are required to be closed. The default is false.

After running, the following html is generated:

<head>
    <meta charset="UTF-8">
    <title>My webpack</title>
    <link href="./style/index.8574a0d53ebeb4201b94.css?8574a0d53ebeb4201b94" rel="stylesheet">
</head>

<body>
    <div id="container"></div>
    <script type="text/javascript" src="index.8574a0d53ebeb4201b94.js?8574a0d53ebeb4201b94"></script>
</body>
<script src="../js/common/jquery.min.js"></script>

</html>


Posted by Kilgore Trout on Wed, 09 Jan 2019 16:57:10 -0800