利用webpack搭建vue3项目

1,021 阅读2分钟

一、你没看错是用webpack!!!

为什么用webpack来搭建企业级项目,而不是vue3的亲儿子vite呢?技术稳定性大于一切,选择webpack可以减少后续很多麻烦。

搭建步骤

  1. 项目目录和源码准备;
  2. 安装依赖;
  3. 配置 Webpack 的 Vue.js 3 编译配置;
  4. 执行 Vue.js 3编译。

第一步:搭建项目结构

.
├── dist/*
├── package.json
├── src
│   ├── app.vue
│   └── index.js
└── webpack.config.js

app.js


<template>
  <div class="demo">
    <div class="text">Count: {{state.count}}</div>
    <button class="btn" @click="onClick">Add</button>
  </div>
</template>

<script setup>
  import { reactive } from 'vue';
  const state = reactive({
    count: 0
  });
  const onClick = () => {
    state.count ++;
  }
</script>

<style>
.demo {
  width: 200px;
  padding: 10px;
  box-shadow: 0px 0px 9px #00000066;
  text-align: center;
}
.demo .text {
  font-size: 28px;
  font-weight: bolder;
  color: #666666;
}
.demo .btn {
  font-size: 20px;
  padding: 0 10px;
  height: 32px;
  min-width: 80px;
  cursor: pointer;
} 
</style>

index.js


import { createApp } from 'vue';
import App from './app.vue';

const app = createApp(App);
app.mount('#app');

第二步:安装依赖


pnpm install vue
pnpm i  css-loader mini-css-extract-plugin vue-loader webpack webpack-cli -D

package.json

{
   "scripts": {
	"build": "webpack -c ./webpack.config.js"
    }, 
  "dependencies": {
	"vue": "^3.2.47"
    },
   "devDependencies": {
	"css-loader": "^6.7.3",
	"mini-css-extract-plugin": "^2.7.2",
	"vue-loader": "^17.0.1",
	"webpack": "^5.75.0",
	"webpack-cli": "^5.0.1"
  }	
}

第三步:webpack配置


const path = require('path');
const { VueLoaderPlugin } = require('vue-loader/dist/index')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  mode: 'production',
  entry: {
    'index' : path.join(__dirname, 'src/index.js'),
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: [
          'vue-loader'
        ]
      },
      {  
        test: /\.(css|less)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
        ]
      },
    ]
  },
  plugins: [
    new VueLoaderPlugin(), 
    new MiniCssExtractPlugin({
      filename: '[name].css'
    })
  ],
  externals: {
    'vue': 'window.Vue'
  }
}

Vue 的加载插件(VueLoaderPlugin)来辅助你在编译 Vue.js 3 代码时候做相关的编译处理。同时,我们这里也用了 CSS 的分离插件(MiniCssExtractPlugin),主要是在 Webpack 打包的生命周期过程中将 Vue.js 3 源码里的 CSS 代码分离出单独的 CSS 文件

最后是 externals,这个是声明在 Webpack 打包编译过程中,有哪些源码依赖的 npm 模块需要“排除打包”处理,也就是不做打包整合处理。我们这里就是将 Vue.js 3 的运行源码进行“排除打包”处理,让代码最终代码依赖的 Vue.js 3 运行时,从 window.Vue 全局变量获取。这么做的好处就是通过减少打包的内容来缩短打包时间

执行 npm run build

开发模式处理


pnpm i --D webpack-dev-server

添加配置


{
  // 其它 Webpack配置代码
  devServer: {
    static: {
      directory: path.join(__dirname),
    },
    compress: true,
    port: 6001,
    hot: false,
    compress: false,
  }
  // 其它 Webpack配置代码
}

{
  // 其它 Webpack配置代码
  devtool: 'inline-cheap-module-source-map', 
  // 其它 Webpack配置代码
}

处理html

npm i --save-dev html-webpack-plugin

配置html-webpack-plugin到webpack.config.js


{
  // 其它 Webpack配置代码
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Hello Vue',
      filename: 'index.html',
      template:'./index.html',
      minify: false,
      inject: false,
      templateParameters: {
        publicPath: path.join(__dirname),
        js: [
          './node_modules/vue/dist/vue.runtime.global.js',
          './index.js'
        ],
        css: [
          './index.css'
        ],
      },
    })
  ]
  // 其它 Webpack配置代码
}

index.html代码


<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <link rel="stylesheet" href="<%= htmlWebpackPlugin.options.templateParameters.css[0] %>" />
    <script src="<%= htmlWebpackPlugin.options.templateParameters.js[0] %>"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script src="<%= htmlWebpackPlugin.options.templateParameters.js[1] %>"></script>
</html>

生产环境

pnpm i -D css-minimizer-webpack-plugin terser-webpack-plugin 

配置webpack.config.js


{
  // 其它 Webpack配置代码
  optimization: {
    minimizer: [
      new TerserPlugin({}),
      new CssMinimizerPlugin({}),
    ],
  },
  // 其它 Webpack配置代码
}

最后加入webpack-merge

pnpm install -D webpack-merge

完整配置


const path = require('path');
const webpackMerge = require('webpack-merge').default;
const { VueLoaderPlugin } = require('vue-loader/dist/index')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');

const baseConfig = {
  mode: process.env.NODE_ENV,
  entry: {
    'index' : path.join(__dirname, 'src/index.js'),
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: [
          'vue-loader'
        ]
      },
      {  
        test: /\.(css|less)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
        ]
      },
      { 
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(), 
    new MiniCssExtractPlugin({
      filename: '[name].css'
    }),  
  ],
  externals: {
    'vue': 'window.Vue'
  }
}

if (process.env.NODE_ENV === 'development') {
  config = webpackMerge(baseConfig, {
    devtool: 'inline-cheap-module-source-map', 
    devServer: {
      static: {
        directory: path.join(__dirname),
      },
      port: 6001,
      hot: false,
      compress: false,
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Hello Vue',
        filename: 'index.html',
        template:'./index.html',
        minify: false,
        inject: false,
        templateParameters: {
          publicPath: path.join(__dirname),
          js: [
            './node_modules/vue/dist/vue.runtime.global.js',
            './index.js'
          ],
          css: [
            './index.css'
          ],
        },
      })
    ]
  })
} else {
  config = webpackMerge(baseConfig, {
    optimization: {
      minimizer: [
        new TerserPlugin({}),
        new CssMinimizerPlugin({}),
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Hello Vue',
        filename: 'index.html',
        template:'./index.html',
        minify: false,
        inject: false,
        templateParameters: {
          publicPath: path.join(__dirname),
          js: [
            'https://unpkg.com/vue@3.2.37/dist/vue.runtime.global.js',
            './index.js'
          ],
          css: [
            './index.css'
          ],
        },
      })
    ]
  })
}

module.exports = config;