1. 程式人生 > 其它 >從0開始基於Webpack5 搭建HTML+Less 前端工程

從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">webpack5</div> <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