从0开始基于Webpack5 搭建HTML+Less 前端工程


          基于Webpack5 搭建HTMl+Less的前端项目

  1. 新建一个文件夹(比如命名为webpack)

  2. 用编辑器打开该文件夹,并在编辑器的终端执行 npm init -y 自动创建package.json 文件

  3. 新建 src/pages/home 目录文件夹 并创建index.html index.js index.less 文件
    index.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><%= htmlWebpackPlugin.options.title %>title>
      head>
      <body>
        <div class="title">webpack5div>
        <div id="app">div>
      body>
    html>

    index.js

    require('./index.less')
    import imgUrl from '@static/images/webpack5.jpeg'
    
    const app = document.getElementById('app')
    var img = new Image()
    img.src = imgUrl
    img.width = 500
    app.appendChild(img)
    

    index.less

    .title {
      font-size: 20px;
      font-weight: bold;
      color: red;
      text-align: center;
    }
    #app{
     text-align: center;
    }
  4.   安装webpak 以及相关插件的包
    #webpack 运行以及html文件生成所用的包
    npm install webpack webpack-cli html-webpack-plugin webpack-dev-server clean-webpack-plugin -D

    # 解析less文件需要的webpack插件
     npm install less less-loader css-loader style-loader -D  

    #抽取 css文件以及压缩css js需要的webpack插件
     npm install mini-css-extract-plugin css-minimizer-webpack-plugin terser-webpack-plugin  -D

    #拷贝静态文件以及图片压缩所需插件(按需使用)(imagemin-webpack-plugin 需要使用cnpm下载用npm启动会报错,原因暂不明,下同) 适用于html中直接引用图片
     npm install  copy-webpack-plugin -D
    cnpm install imagemin-webpack-plugin -D

    #引用图片以及压缩 适用于js中创建img添加图片地址
    npm install url-loader filer-loader -D
    cnpm install image-webpcak-loader -D
    
    
    

    也可以用cnpm yarn 等安装

  5. 创建 webpack.config,js   (webpack 配置文件)
    webpack.config.js
    const path = require('path') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const CssMinimizerPlugin = require('css-minimizer-webpack-plugin') const TerserJSPlugin = require('terser-webpack-plugin') // const CopyPlugin = require('copy-webpack-plugin') // const ImageminPlugin = require('imagemin-webpack-plugin').default const { extendDefaultPlugins } = require('svgo')
    module.exports = (env) => {   const mode = env.production ? 'production' : 'development'
      return {     entry: { home: path.resolve('src/pages/home/index.js') },     output: {       path: path.resolve('dist'),       filename: '[name].[chunkhash].js',     },     mode,     resolve: {       alias: {         '@static': path.resolve('static'),       },     },     module: {       rules: [         {           test: /\.less$/i,           use: [             // 解析less 并抽离css,开发环境用syle-loader便于热更新             env.production ? MiniCssExtractPlugin.loader : 'style-loader',             'css-loader',             'less-loader',           ],         },         {           test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,           use: [             {               loader: 'url-loader',               options: {                 limit: 8192,               },             },             {               loader: 'image-webpack-loader',             },           ],         },       ],     },     plugins: [       // 清空dist(打包文件夹)下所有文件       new CleanWebpackPlugin(),       // 创建HTML页面,webpack output主要负责提取压缩的js文件,需要用这个插件生成HTML文件       new HtmlWebpackPlugin({         filename: `index.html`, //生成的文件名         template: `./src/pages/home/index.html`, //文件模板不穿会生成一个默认Body内容为空的HTML文件         inject: true,         title: 'webpack5',         favicon: path.resolve(__dirname, 'static/ico/favicon.ico'),         chunks: ['home'], // chunks为该页面要包含的js文件       }),       // new HtmlWebpackPlugin(),       new MiniCssExtractPlugin({         filename: 'css/[name].[contenthash:8].css',       }),       // 根据实际情况使用       // new CopyPlugin({       //   patterns: [       //     {       //       from: 'static',       //       to: 'static',       //     },       //   ],       // }),       // 放在CopyPlugin之后可以压缩copy的图片资源       //  new ImageminPlugin({ test: /\.(jpe?g|png|gif|svg)$/i }),     ],     optimization: {       minimize: true,       minimizer: [         new CssMinimizerPlugin({}),         new TerserJSPlugin({           terserOptions: {             format: {               comments: false,             },             compress: {               drop_console: true, // 默认false,设置为true, 则会删除所有console.* 相关的代码。             },           },           extractComments: false,         }),       ],     },     devServer: {       // watchFiles: ['src', 'static'],       hot: true,       compress: true,       port: 8000,       open: true,     },   } }
  6. 在packge.json 配置执行脚本
    { 
     ...
     "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "webpack-dev-server",
        "build": "webpack --env production"
      },
      ....
    }
  7. 执行 npm start 命令就会自动打开浏览器访问页面

  8. gitee项目地址 https://gitee.com/jilangyangbo/webpack5.git