The five modules

  • entry
  • output
  • module
  • plugin
  • mode
// npm i webpack webpack-cli
const { resolve } = require('path');
module.exports={
    entry: ['./src/index.js'].output: {filename:'bundle.js'.path:resolve(__dirname,'dist')},module: {rules:[]
    },
    plugins: [].mode:'development' //production
}
Copy the code

Parsing file classification

Style files, JS, HTML, images

style

  • parsingcss,less
// npm i style-loader css-loader less less-loader
module.exports={
    module: {rules:[
            {
            	test:/\.css$/,
                use:[ // Loader executes in reverse order
                  'style-loader'.// Create a style tag to insert the js style resource into the head
                  'css-loader' // Load the CSS file as a commonJS module into js, which contains the style string] {},test:/\.less$/,
                use:[
                  'style-loader'.'css-loader'.'less-loader' To compile less files into CSSS files, install the less package]}]},}Copy the code
  • The style is compatible withpostcss
module.exports={
	// NPM I postCSs-loader postCSs-preset -env (plugin)
    module: {rules:[
            {
            	test:/\.css$/,
                use:[ // Loader executes in reverse order
                  'style-loader'.// Create a style tag to insert the js style resource into the head
                  {
                     loader:'postcss-loader'.options: {ident:'postcss'./* postcss-preset-env helps PostCSS read browserslist's configuration in package.json Browserslist's specified compatibility configuration */
                        plugins:() = >[require('postcss-preset-env') (the)]}},'css-loader' // Load the CSS file as a commonJS module into js, which contains the style string]}]},}Copy the code

package.json

{
  "browserslist": {Webpack.config. js process.env.node_env = 'development'; * /
      "development": ["last 1 chrome version" // Compatible with the latest browser version
        "last 1 firefox version"].// Default production environment
      "production": ["0.2%" >.// Greater than 99.8 browser
        "not dead".// Not compatible with dead browsers
        "not op_mini all" // Not compatible with Openg]}}Copy the code
  • extractcssFor a separate file plug-inmini-css-extract-plugin
// npm i mini-css-extract-plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports={
    module: {rules:[
            {
            	test:/\.css$/,
                use:[
                   {
                   /* This loader will replace style-loader to extract CSS files from JS. The development configuration needs to use style-loader to configure devServer hot to implement style hot update */
                     loader: MiniCssExtractPlugin.loader, 
                    // Modify the default loader configuration
                     options: {
                       // Complete the path where the page imported resources
                       publicPath: '.. / ',}}, {loader:'postcss-loader'.options: {ident:'postcss'.plugins:() = >[require('postcss-preset-env') (the)]}},'css-loader']]}},plugins: [new MiniCssExtractPlugin({
        // Rename the file
        filename: 'css/main.css',}})]Copy the code

js

Webpack itself can handle JS files, all it needs to do is compatibility

  • Basic compatibility
// NPM I babel-loader @babel/ core@babel /preset-env
module.exports={
    module: {rules:[
            {
            	test:/\.js$/,
                loader:'babel-loader'.options: {exclude:/node_modules/.// Compatible browser package.json browserslist is required
                // Default: tell Babel what compatibility processing to do
                  presets:["@babel/preset-env"]}}]},}Copy the code
  • Code compatibility handling of native apis not supported by browsers
    • Methods a
      // Install package NPM i@babel /polyfillSimply introduce Babel/Polyfill in the public JS pageimport 'babel/polyfill'Disadvantages All compatibility methods are introduced, increasing file sizeCopy the code
    • Method 2 import on demand
      // Install NPM I core-js
      module.exports={
          module: {rules:[
                  {
                      test:/\.js$/,
                      loader:'babel-loader'.options: {exclude:/node_modules/,
                        presets:[
                        [
                        "@babel/preset-env",
                         {
                           useBuiltIns:'usage'.// Load as needed
                           corejs: {version:3}, // Specify the version of core-jsThe targets: {// Specify a browser-compatible version
                             chrome:'60'.firefox:'60'.ie:'9'}}]]}}]},}Copy the code
  • The compressioncss
// npm i optimize-css-assets-webpack-plugin
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
module.exports={
  pliguns: [new OptimizeCssAssetsWebpackPlugin()]
}
Copy the code

htmlThe template

// npm i html-webpack-plugin
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports={
  plugins: [new htmlWebpackPlugin({
       // Copy the template file, create HTML and automatically import the output file
      tempalte:'./index.html'.// Compress the code
      minfy: {collapseWhitespace:true.// Remove whitespace
        removeComments:true.// Remove comments}}})]Copy the code

The picture

// npm i url-loader file-loader
module.exports={
  module: {rules:[
      {
        test:/\.(jpg|png|gif)$/./ / url - loader depend on file - loader
        loader:'url-loader'.options: {/* Image size smaller than 8KB, base64 in JS advantage: reduce the number of requests Disadvantages: large image size, slow file request */
          limit: 8*1024./ / the nuptial
          name:'[hash:10].[ext]'.// Output path
          outputPath:'imags'}}]}}Copy the code

devSearver

/* NPM I webpack-dev-server build enable NPX webpack-dev-server */
module.exports={
  devServer: {// Project build path
    constBase:resolve(__dirname,'dist'),
    port:3030.// Enable compression
    compress:true.// Automatically open the browser
    open:true./* Enable HMR function (hot update) style file style-loader implements HMR js file does not use HMR */ by default
    hot:true}}Copy the code