Webpack打包简单页面

60 阅读1分钟
|-- src
        |-- index.css
        |-- index.html
        |-- index.js
        |-- assets
            |-- images
//webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');//这里如果css从html引入时要用style-loader生成style标签,用MiniCssExtractPlugin需要将css从js中引入

module.exports = {
  devtool: 'eval-source-map',
  mode: 'production',
  output: {
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  module: {
    rules: [
      // 处理 CSS
      {
        test: /.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      },
      // 处理图片
      {
        test: /.(png|svg|jpe?g|gif)$/,
        type: 'asset',
        generator: {
          filename: 'assets/images/[name][ext][query]'
        },
      },
      {
        test: /.html$/,
        loader: 'html-loader'
      }
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: 'css/[contenthash].css' }),
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
  ],
  devServer: {
    static: {
      directory: path.join(__dirname, 'public')
    },
    hot: true,
    compress: true,
    port: 9000,
  },
  performance: {
    hints: false
  }
};
  "scripts": {
    "build": "npx webpack",
    "start":"webpack server"
  },