webpack使用与常用配置
@ 姜波 | 星期日,六月 21 日,2020 年 | 1 分钟阅读 | 更新于 星期日,六月 21 日,2020 年

Webpack使用

安装

npm init -y
npm install webpack webpack-cli -D
// 或者
npm install webpack -g

"scripts": {
    "build": "webpack",
    "watch": "webpack --watch",
    "dev": "webpack-dev-server",
 }

创建webpack.config.js

入口

module.exports = {
  entry: './src/index.js',
};

输出

const path = require('path');

module.exports = {
  output: {// 出口
    path: path.join(__dirname, './dist'),
    filename: 'bundle.js'
  }
};

loader

npm install css-loader style-loader sass-loader node-sass -D

module.exports = {
  module: {
    rules: [
      { 
        test: /\.css$/, use:['style-loader','css-loader']
      },
      { 
        test: /\.(scss|sass)$/, use:['style-loader','css-loader','sass-loader']
      }
    ]
  }
};

plugin

npm install --save-dev html-webpack-plugin

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  plugins: [new HtmlWebpackPlugin({
  		filename: 'index.html',
      template: 'src/assets/index.html'
  })]
};

模块热替换

npm install --save-dev webpack-dev-server

const webpack = require('webpack');

module.exports = {
  devServer: {
  	hot: true,
    contentBase: './dist'
  },
  plugins:[new webpack.HotModuleReplacementPlugin()]
};

mode

module.exports = {
  mode: 'production'
};

其他配置

babel

npm install -D babel-loader @babel/core @babel/preset-env @babel/plugin-transform-runtime
npm install -S @babel/runtime

创建.babelrc
{
  "presets": ["@babel/preset-env"],
  "plugins": ["@babel/plugin-transform-runtime"]
}

webpack.config.js
module.exports = {
  module: {
    rules: [
      { 
        test: /\.js$/, loader:['babel-loader']
      }
    ]
  }
};

清空、拷贝文件

npm install --save-dev clean-webpack-plugin copy-webpack-plugin

webpack.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
    plugins: [
     	new CleanWebpackPlugin(),
      new CopyPlugin([
        { from: path.join(__dirname, 'assets'), to: 'assets' }
    	]),
    ]
}

最小化生产

npm install optimize-css-assets-webpack-plugin terser-webpack-plugin mini-css-extract-plugin -D

webpack.config.js
const TerserJSPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

module.exports = {
  optimization: {
    minimizer: [
      new TerserJSPlugin({}),
      new OptimizeCSSAssetsPlugin({})
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,// style-loader换成MiniCssExtractPlugin.loader
          "css-loader",'sass-loader'
        ]
      }
    ]
  }
};

公众号

Image text

QQ

Image text

微信

Image text

微信打赏

Image text

社交链接