Webpack 懂的都懂系列

webpack.config.js:

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizePlugin = require('css-minimizer-webpack-plugin')

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

  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, './dist'),
    clean: true,
    assetModuleFilename: 'images/[contenthash][ext]'
  },

  devtool: 'inline-source-map',

  mode: 'production',

  devServer: {
    static: './dist'
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: 'public/index.html',
      filename: 'app.html',
      inject: 'body'
    }),
    new MiniCssExtractPlugin({
      filename: '/css/[contenthash].css'
    })
  ],

  module: {
    rules: [
      {
        test: /\.(jpeg|png)$/,
        type: 'asset/resource'
      },
      {
        test: /\.txt$/,
        type: 'asset/source'
      },
      {
        test: /\.(css|less)$/,
        use: [ MiniCssExtractPlugin.loader, 'css-loader', 'less-loader' ]
      }
    ]
  },

  optimization: {
    minimizer: [
      new CssMinimizePlugin() // mode 为 production 才会生效
    ]
  }
}

package.json:

{
  "name": "webpack-01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "npx webpack",
    "server": "npx webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^6.5.1",
    "css-minimizer-webpack-plugin": "^3.2.0",
    "html-webpack-plugin": "^5.5.0",
    "less": "^4.1.2",
    "less-loader": "^10.2.0",
    "mini-css-extract-plugin": "^2.4.5",
    "npx": "^10.2.2",
    "style-loader": "^3.3.1",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.6.0"
  }
}

dist/app.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webpack-01</title>

  <link href="/css/12b52682f3040bb1646a.css" rel="stylesheet"></head>

<body>
  
  <script defer src="app.js"></script>

</body>
</html>

src/hello.js:

function hello () {
  console.log('hello!!! webpack')
}

export default hello

src/index.js:

项目结构:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值