[01] webpack4 Quick Start

This article is for novices get started quickly webpack4, talk about the application, is relatively shallow.

Open webpack tour

First, the simple configuration

1, initialize the project

  npm init

//packge.json 文件中
"scripts": {    
    "build": "webpack  --profile --progress --colors --display-error-details",    
    "dev": "webpack  --display-modules --profile --progress --colors --display-error-details"  
}, 
// Color output with color, such as: will be displayed in red time-consuming steps 
// Profile output performance data, you can see each step takes 
// Progress output progress for the current compilation, presented as a percentage 
/ / Run the display-modules in the case of a default modules will be hidden node_modules, add this parameter can display these hidden module 
// Run the display-error-output detailed error information the Details

2, installation webpack

  Global Installation: npm install webpack -g
  local installation: NPM the install WebPACK WebPACK -D-CLI

3, WebPACK core concepts

  Entry:  entry, the first step in execution of the build Webpack Entry will start, can be abstracted as an input. Module: module, where everything is in Webpack module, a module corresponds to a file. Chunk:  code block, a combination of a plurality of modules made Chunk, code for merging and segmentation. Loader: Module converter module for converting the original content into the new content on demand. Plugin:  extension, in particular the timing of the build process Webpack injection expansion logic to change the results of the build or do what you want. Output: output, in Webpack after a series of treatment and obtain the desired output code will eventually result.
  
  
  
  
  

4, configuration  webpack.config.js

path = the require the let ( 'path'); // Node module 
module.exports = {
    entry: './src/index.js', // entry file 
    output: {
        filename: 'build.js', // export file 
        // This path must be absolute 
        path: path.resolve ( './ dist' )
    }, 
    devserver: {}, // development server 
    Module1: {}, // module configuration 
    plugins: [], // plugin configuration 
    MODE: 'Development', // may change the mode 
    Resolve: {}, // configuration parsing 
}

  Here or use the command npm run dev npm run build can be packaged js file.

Second, the development server configuration

  npm i webpack-dev-server –D

//webpack.config.js
devServer:{
    ContentBase: path.resolve (__ dirname, 'dist'), // configuration files in the root directory of development services running 
    Host: 'localhost', // development server is listening host address 
    the compress: to true ,    // development server is started gzip, etc. compression 
    port: 8080,        // development server listening on port 
    open: to true          // whether to automatically open the browser 
}
//package.json
"scripts": {
    "dev": "webpack-dev-server --open --mode development "
}
// enable local service RUN dev npm 
// --mode Development --mode production development environment or a production environment

Third, the configuration module

  test: the matching process the file extension of regular expressions

  use: Loader name, is the name of the module you want to use

  include / exclude: File must be handled manually specify the folder or folders masking process need not

  query: provides additional options for setting loaders

1, support for loading css file

  npm install style-loader css-loader -D

module: {
    rules:[
       {
            test:/\.css$/,
            use:['style-loader','css-loader'],
            include:path.join(__dirname,'./src'),
            exclude:/node_modules/
       }        
    ]
}
// Note: loader loading order is from right to left. Css-loader which is to use analytical style-loader then added css file parsed into Head label.

2, support picture

  npm install file-loader url-loader html-withimg-loader -D

module: {
    rules:[ 
       {
            test: /\.(png|jpg|gif|svg|bmp|eot|woff|woff2|ttf)$/,
            loader: {
                loader: 'url-loader',
                options: {
                    limit: . 5 * 1024, // picture size> limit the use of file-loader, on the contrary-Loader using URL 
                    OutputPath: 'Images /' // specified position packetized image 
                }
            }
        }
    ]
}
// Usage - added manually: 
the let the require logo = ( './ Images / logo.png' );
let img = new Image();
img.src = logo;
document.body.appendChild(img);

// Usage - introduced pictures in the CSS 
.img- BG {
    background: url(./images/logo.png);
    width:173px;
    height:66px;
}

// Usage - use images in HTML 
{
    test:/\.(html|html)$/,
    use:'html-withimg-loader',
    include:path.join(__dirname,'./src'),
    exclude:/node_modules/
}

3. Compile less and sass

  npm install less less-loader node-sass sass-loader -D

// the compiled code in which head 
module: {
    rules:[ 
        {
            test: /\.css$/,
            loader: ['style-loader', 'css-loader']
        }, {
            test: /\.less$/,
            loader: ['style-loader', 'css-loader']
        }, {
            test: /\.scss$/,
            loader: ['style-loader', 'css-loader']
        }
    ]
}

4, the process attribute prefix css3

  npm install postcss-loader autoprefixer -D

// postcss.config.js file 
module.exports = {
    plugins: [
        require('autoprefixer')
    ]
}
// the post-laoder push the loader css array of 
module: {
    rules:[ 
        {
            test: /\.css$/,
            loader: ['style-loader', 'css-loader', 'postcss-loader']
        }, {
            test: /\.less$/,
            loader: ['style-loader', 'css-loader', 'less-loader']
        }, {
            test: /\.scss$/,
            loader: ['style-loader', 'css-loader', 'sass-loader']
        }
    ]
}

5, the escape ES6 / ES7 / JSX

  npm i babel-core babel-loader babel-preset-env babel-preset-stage-0 babel-preset-react -D

// create .babelrc file 
{
     "the Presets": [ "@ babel / PRESET-env" ],
     "plugins" : [
        [
            "@babel/plugin-transform-runtime",
            {
                "corejs": 3
            }
        ]
    ]
}
module: {
    rules:[ 
        {
            test:/\.jsx?$/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ["env","stage-0","react"]// env --> es6, stage-0 --> es7, react --> react
                }
            },
            include:path.join(__dirname,'./src'),
            exclude:/node_modules/
        }
    ]
}

Fourth, configure plugins

1, automatic output html

  npm install html-webpack-plugin -D

const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
    new HtmlWebpackPlugin({
        Template: './src/index.html',    // specify the output template 
        filename: 'base.html',           // output file name 
        of chunks are: [ 'the Common', 'Base'],      // in production an HTML file in which the introduction of a code block 
        : hash to true ,                      // name is a hash value 
        title: 'Base',                   // you can call htmlWebpackPlugin.options.title to set the variable names in the template html template that can be used 
        minify: {                        // to html file compression 
            removeAttributeQuotes: to true  // remove the double quotes 
        }
    })
]

2, separated css

  npm install extract-text-webpack-plugin@next -D

// the compiled code in a separate file which 
const = ExtractTextWebpackPlugin the require ( 'Extract-text-WebPACK-plugin' );
let cssExtract = new ExtractTextWebpackPlugin('css.css');
let lessExtract = new ExtractTextWebpackPlugin('less.css');
let sassExtract = new ExtractTextWebpackPlugin('sass.css');

module: {
    rules: [
         {
            test: /\.css$/,
            loader: cssExtract.extract({
                use: ['css-loader?minimize']
            })
        }, {
            test: /\.less$/,
            loader: lessExtract.extract({
                use: ['css-loader?minimize', 'less-loader']
            })
        }, {
            test: /\.scss$/,
            loader: sassExtract.extract({
                use: ['css-loader?minimize', 'sass-loader']
            })
        }
    ]
},
plugins: [
    cssExtract,
    lessExtract,
    sassExtract
]
// process the image path problem 
const PUBLIC_PATH = '/' ;
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath:PUBLIC_PATH
}

3, copy static files ( sometimes not referenced in the project file also need to be packaged into the target directory )

  npm install copy-webpack-plugin -D

const CopyWebpackPlugin = require('copy-webpack-plugin');

plugins: [
    new CopyWebpackPlugin([{
        from: path.join (__ dirname, 'public'),        // copy where 
        to: path.join (__ dirname, 'dist', 'public')   // Copy Where 
    }])
]

4, before packing to empty the output directory

  npm install clean-webpack-plugin -D

const CleanWebpackPlugin = require('clean-webpack-plugin');

plugins: [
    new CleanWebpackPlugin([path.join(__dirname, 'dist')])
]

5, compression JS

  npm install uglifyjs-webpack-plugin -D

const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');

plugins: [
    new UglifyjsWebpackPlugin()
]

Fifth, the proxy server

// request to / api / users will now be delegated to the request http: // localhost: 9000 / api / users. 
devServer: {
    proxy: {
        "/api": "http://localhost:9000",
    }
}

// remove the request path '/ API' 
devserver: {
    proxy: {
        '/api': {
            target: 'http://localhost:4000',
            Pthriawrite: {
                '/api': ''
            }
        }
    }
}

Six, relove resolve

1、extensions

// After specifying the file name plus the extension may not require or import extension in time, will in turn try to add extensions to match 
Resolve: {
     // autocomplete suffixes, attention must first be an empty string, to a certain suffix point at the beginning 
   Extensions: [. "", "JS", "CSS", "json.". ],
},

2、 alias

// configure an alias module can accelerate the speed to find webpack 
// Whenever introducing jquery modules, it will directly introduced jqueryPath, without the need to press Search to find the rules module from node_modules folder 
// do not need webpack to resolve jquery. js file 
const = path.join on Bootstrap (__ dirname, 'the node_modules / on Bootstrap / dist / CSS / bootstrap.css' );
resolve: {
    alias: {
        'bootstrap': bootstrap
    }
}

Seven multi-entry file

// Sometimes we can be more than one page HTML page, there will be multiple pages, so we need more entrance 
// multiple entry, html template can be added to each entry 
entry: {
    index: './src/index.js',
    main:'./src/main.js'
},
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[hash].js',
    publicPath:PUBLIC_PATH
},

plugins: [
    new HtmlWebpackPlugin({
        minify: {
            removeAttributeQuotes:true
        },
        hash: true,
        template: './src/index.html',
        chunks:['index'],
        filename:'index.html'
    }),
    new HtmlWebpackPlugin({
        minify: {
            removeAttributeQuotes:true
        },
        hash: true,
        chunks:['login'],
        template: './src/login.html',
        filename:'login.html'
    })]
]

Guess you like

Origin www.cnblogs.com/MaShuai666/p/12508077.html
Recommended