webpack快速入门

生产环境作用:

能让代码优化上线运行的环境,要注意文件大小优化,兼容等方面

执行命令:

npx webpack

提取css成单独文件

安装包
# 指定版本,命令输入在一行
npm i -D webpack@5.36.2 webpack-cli@4.7.0 mini-css-extract-plugin@1.6.0 css-loader@5.2.4 html-webpack-plugin@5.3.1
#逐个依次安装
npm i -D webpack@5.36.2 
npm i -D webpack-cli@4.7.0  
npm i -D css-loader@5.2.4 
npm i -D html-webpack-plugin@5.3.1
#新增
npm i -D mini-css-extract-plugin@1.6.0
配置
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//导入包
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          // 这个loader取代style-loader。作用:提取js中的css成单独文件
          MiniCssExtractPlugin.loader,
          // 将css文件整合到js文件中
          'css-loader'
        ]
      }                    
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
      // 对输出的css文件进行重命名
      filename: 'css/bundle.css'
    })
  ]
};

css兼容性处理

安装包
# 新增
npm i -D postcss-loader@5.2.0 postcss-preset-env@6.7.0

#逐个依次安装
npm i -D postcss-loader@5.2.0
npm i -D postcss-preset-env@6.7.0

配置

//webpack.config.js中
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// 设置nodejs环境变量,默认是production
process.env.NODE_ENV = 'development';
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          // 修改loader的配置
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [require('postcss-preset-env')()]
              }
            }
          }            
        ]
      }      
    ]
  }, plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
      filename: 'css/build.css'
    })
  ]
};
// 在package.json中添加browserslist键值实现配置,通过配置加载指定的css兼容性样式
 "browserslist": {
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  }
说明

如果出现错误,到https://www.npmjs.com/上查看用法更新

压缩css

安装包
# 新增
npm i -D optimize-css-assets-webpack-plugin@5.0.4

说明:

The optimize-css-assets-webpack-plugin@4.0.0 version and above supports webpack v4.

根据上面信息,对webpack v4支持,没提到对webpack v5支持。

//会出现下面信息,经测试不影响压缩
(node:12932) [DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)
(Use `node --trace-deprecation ...` to show where the warning was created)

关注网址:https://www.npmjs.com/package/optimize-css-assets-webpack-plugin 看支持最新信息

配置
//接css兼容性处理的配置,进行添加
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
//导入包
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [require('postcss-preset-env')()]
              }
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
      filename: 'css/build.css'
    }),
     // 压缩css
    new OptimizeCssAssetsWebpackPlugin()
  ]
};

js语法检查

旧版

安装包

npm i -D webpack@5.36.2 webpack-cli@4.7.0 html-webpack-plugin@5.3.1
npm i eslint-config-airbnb-base eslint-plugin-import eslint eslint-loader -D

配置

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          // 自动修复eslint的错误
          fix: true
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ],
  mode: 'development'
};

// 在package.json中添加eslintConfig中设置
"eslintConfig": {
  "extends": "airbnb-base"
}

说明

  • 在js中下一行不进行eslint检查,在js中添加 // eslint-disable-next-line 则 console.log("aaa");这一行不检查。

    //在./src/js/index.js中
    // eslint-disable-next-line
    console.log("aaa");
    

使用eslint-webpack-plugin替换旧版eslint-loader

安装包:
# 指定版本,命令输入在一行
npm i -D webpack@5.36.2 webpack-cli@4.7.0 html-webpack-plugin@5.3.1 eslint@7.26.0 eslint-config-airbnb-base@14.2.1 eslint-plugin-import@2.22.1 eslint-webpack-plugin@2.5.4

# 逐个依次安装
npm i -D webpack@5.36.2
npm i -D webpack-cli@4.7.0
npm i -D html-webpack-plugin@5.3.1
# 新增
npm i -D eslint@7.26.0
npm i -D eslint-config-airbnb-base@14.2.1
npm i -D eslint-plugin-import@2.22.1
npm i -D eslint-webpack-plugin@2.5.4

配置
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new ESLintPlugin({
      fix: true,
      extensions: ['js', 'json', 'coffee'],
      exclude: '/node_modules/'
    })
  ],
  mode: 'development'
};
// 在package.json中添加eslintConfig中设置
"eslintConfig": {
  "extends": "airbnb-base"
}
说明:

在js中哪一行不进行eslint检查, 在在上面想添加 // eslint-disable-next-line

js兼容性处理

安装包
# 指定版本,命令输入在一行
npm i -D babel-loader@8.2.2 @babel/core@7.14.0 @babel/preset-env@7.14.1 core-js@3.12.1

# 逐个依次安装
#新增
npm i -D babel-loader@8.2.2
npm i -D @babel/core@7.14.0
npm i -D @babel/preset-env@7.14.1
npm i -D core-js@3.12.1

配置
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          // 预设:指示babel做怎么样的兼容性处理
          presets: [
            [
              '@babel/preset-env',
              {
                // 按需加载
                useBuiltIns: 'usage',
                // 指定core-js版本
                corejs: {
                  version: 3
                },
                // 指定兼容性做到哪个版本浏览器
                targets: {
                  chrome: '60',
                  firefox: '60',
                  ie: '9',
                  safari: '10',
                  edge: '17'
                }
              }
            ]
          ]
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ],
  mode: 'development'
};

// 在package.json中添加browserslist键值实现配置,通过配置加载指定的js兼容性样式,同css兼容性处理可以一样
 "browserslist": {
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  }

js压缩

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ],
  // 生产环境下会自动压缩js代码
  mode: 'production'
};

html压缩

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      // 压缩html代码
      minify: {
        // 移除空格
        collapseWhitespace: true,
        // 移除注释
        removeComments: true
      }
    })
  ],
  mode: 'production'
};

二、生产环境配置(综合配置)

初始化

# 初始化项目
npm init -y

# 指定版本,命令输入在一行
npm i -D webpack@5.36.2 webpack-cli@4.7.0 style-loader@2.0.0 css-loader@5.2.4 less@4.1.1 less-loader@8.1.1 html-webpack-plugin@5.3.1 html-loader@2.1.2 file-loader@6.2.0 url-loader@4.1.1 mini-css-extract-plugin@1.6.0 postcss-loader@5.2.0 postcss-preset-env@6.7.0 optimize-css-assets-webpack-plugin@5.0.4 eslint@7.26.0  eslint-config-airbnb-base@14.2.1  eslint-plugin-import@2.22.1  eslint-webpack-plugin@2.5.4 babel-loader@8.2.2  @babel/core@7.14.0  @babel/preset-env@7.14.1  core-js@3.12.1

#逐个依次安装
npm i -D webpack@5.36.2 
npm i -D webpack-cli@4.7.0 
npm i -D style-loader@2.0.0 
npm i -D css-loader@5.2.4
npm i -D less@4.1.1
npm i -D less-loader@8.1.1
npm i -D html-webpack-plugin@5.3.1
npm i -D html-loader@2.1.2
npm i -D file-loader@6.2.0
npm i -D url-loader@4.1.1
npm i -D mini-css-extract-plugin@1.6.0
npm i -D postcss-loader@5.2.0
npm i -D postcss-preset-env@6.7.0
npm i -D optimize-css-assets-webpack-plugin@5.0.4
npm i -D eslint@7.26.0 
npm i -D eslint-config-airbnb-base@14.2.1 
npm i -D eslint-plugin-import@2.22.1 
npm i -D eslint-webpack-plugin@2.5.4
npm i -D babel-loader@8.2.2 
npm i -D @babel/core@7.14.0 
npm i -D @babel/preset-env@7.14.1 
npm i -D core-js@3.12.1

配置

//webpack.config.js中
const { resolve } = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
// 定义nodejs环境变量:决定使用browserslist的哪个环境
process.env.NODE_ENV = 'production';
// 复用loader
const commonCssLoader = [
  MiniCssExtractPlugin.loader,
  'css-loader',
  {
    loader: 'postcss-loader',
    options: { postcssOptions: { plugins: [require('postcss-preset-env')()] } }
  }
];
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [...commonCssLoader]
      },
      {
        test: /\.less$/,
        use: [...commonCssLoader, 'less-loader']
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                useBuiltIns: 'usage',
                corejs: { version: 3 },
                targets: { chrome: '60', firefox: '50', ie: '9', safari: '10', edge: '17' }
              }
            ]
          ]
        }
      },
      {
        test: /\.(jpg|png|gif)/,
        loader: 'url-loader',
        options: { limit: 8 * 1024, name: '[hash:10].[ext]', outputPath: 'imgs', esModule: false }
      },
      {
        test: /\.html$/,
        loader: 'html-loader',
        options: {
          esModule: false,
        }
      },
      {
        exclude: /\.(js|css|less|html|jpg|png|gif)/,
        loader: 'file-loader',
        options: { outputPath: 'media' }
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/bundle.css'
    }),
    new OptimizeCssAssetsWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true
      }
    }),
 	new ESLintPlugin({
      fix: true,
      extensions: ['js', 'json', 'coffee'],
      exclude: '/node_modules/'
    })
  ],
  mode: 'production'
};

// 在package.json中添加browserslist和eslintConfig配置
 "browserslist": {
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  },
"eslintConfig": {
  "extends": "airbnb-base"
}

说明

  • 入口路径: './src/js/index.js'

  • js输出路径: './dist/js/bundle.js'

  • 输出目录: path: resolve(__dirname, 'dist')

  • index.html模板入口路径: './src/index.html'

  • index.html模板输出路径:'./dist/index.html'

  • 处理图片资源配置中出现的outputPath: 'imgs'为设置图片输出目录,在'./dist/imgs/'目录里

  • 处理其他资源配置中出现的outputPath: 'media'为设置其他资源输出目录,在'./dist/media/'目录里

  • 目录划分

    • ./scr/js 存放js文件
    • ./src/imgs 存放图片
    • ./src/css 存放css
    • ./src/media 存放其他资源,比如字体
  • 执行命令:npx webpack

旧版

初始化

最新版本安装(可能出现兼容性问题)

npm init -y
//package.json中devDependencies里添加下面部分
	"@babel/core": "^7.14.0",
    "@babel/preset-env": "^7.14.1",
    "babel-loader": "^8.2.2",
    "core-js": "^3.12.0",
    "css-loader": "^5.2.4",
    "eslint": "^7.26.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-loader": "^4.0.2",
    "eslint-plugin-import": "^2.22.1",
    "file-loader": "^6.2.0",
    "html-loader": "^2.1.2",
    "html-webpack-plugin": "^5.3.1",
    "less": "^4.1.1",
    "less-loader": "^8.1.1",
    "mini-css-extract-plugin": "^1.6.0",
    "optimize-css-assets-webpack-plugin": "^5.0.4",
    "postcss-loader": "^5.2.0",
    "postcss-preset-env": "^6.7.0",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.36.2",
    "webpack-cli": "^4.7.0"
npm install .

配置

//webpack.config.js中
const { resolve } = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 定义nodejs环境变量:决定使用browserslist的哪个环境
process.env.NODE_ENV = 'production';
// 复用loader
const commonCssLoader = [
  MiniCssExtractPlugin.loader,
  'css-loader',
  {
    loader: 'postcss-loader',
    options: { postcssOptions: { plugins: [require('postcss-preset-env')()] } }
  }
];
module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/bundle.js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [...commonCssLoader]
      },
      {
        test: /\.less$/,
        use: [...commonCssLoader, 'less-loader']
      },
      //当一个文件要被多个loader处理,那么一定要指定loader执行的先后顺序: 
      {
        // 在package.json中eslintConfig --> airbnb
        test: /\.js$/,
        exclude: /node_modules/,
        enforce: 'pre',		// 优先执行设置
        loader: 'eslint-loader',
        options: {
          fix: true
        }
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                useBuiltIns: 'usage',
                corejs: { version: 3 },
                targets: { chrome: '60', firefox: '50', ie: '9', safari: '10', edge: '17' }
              }
            ]
          ]
        }
      },
      {
        test: /\.(jpg|png|gif)/,
        loader: 'url-loader',
        options: { limit: 8 * 1024, name: '[hash:10].[ext]', outputPath: 'imgs', esModule: false }
      },
      {
        test: /\.html$/,
        loader: 'html-loader',
        options: {
          esModule: false,
        }
      },
      {
        exclude: /\.(js|css|less|html|jpg|png|gif)/,
        loader: 'file-loader',
        options: { outputPath: 'media' }
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/bundle.css'
    }),
    new OptimizeCssAssetsWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true
      }
    })
  ],
  mode: 'production'
};

// 在package.json中添加browserslist和eslintConfig配置
 "browserslist": {
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  },
"eslintConfig": {
  "extends": "airbnb-base"
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reg183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值