webpack搭建vue脚手架

初始化项目

npm init -y

安装webpack相关

npm i  webpack webpack-cli webpack-dev-server -D

安装解析vue的插件

npm i vue  vue-loader vue-template-compiler vue-style-loader -D

根目录下创建webpack.config.js文件

这里注意vue-loader不支持oneOf 不然会报错

const path = require('path')

//  引入vue-loader的内置插件
const {VueLoaderPlugin} = require('vue-loader')


module.exports = {
    // 配置入口文件
    entry:'./src/main.js',
    // 配置文件的出口
    output:{
        path:path.resolve(__dirnamem, 'dist'),
        filename:'main.js'
    },
    // 配置loader
    module:{
        rules:[
            {
                test:/\.vue$/i,
                use:['vue-loader']
            }
        ]
    },
    plugins:[
        new VueLoaderPlugin(),
    ]
}

创建html模板

public/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>Document</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>

安装解析生产html插件

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

配置

// 引入 html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')


    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),

解析样式

npm i css-loader less-loader postcss-loader postcss-preset-env style-loader --save-dev
            {
                test:/\.vue$/i,
               loader: 'vue-loader'
            },
            {
                test:/\.css$/i,
                use:['stylel-loader', 'css-loader']
            },
            {
                test:/\.less$/i,
                use:['stylel-loader','css-loader', 'less-loader']
            },

安装postcss-preset-env 能解决css大多数样式兼容性问题 需要和packjson.js中的browserslist指定兼容性配合使用

packjson.js

"browserslist": [
    "last 2 version",
    "> 1%",
    "not dead"
  ]

封装样式loader

const getStyleLoaders = (pre) => {
  return [
    "style-loader",
    "css-loader",
    {
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: [
            "postcss-preset-env", // 需要安装postcss-preset-env 能解决css大多数样式兼容性问题 和packjson.js中的browserslist来指定兼容性
          ],
        },
      },
    },
    pre
  ].filter(Boolean);
};
            {
                test:/\.vue$/i,
               loader: 'vue-loader'
            },
            {
                test:/\.css$/i,
                use: getStyleLoaders()
            },
            {
                test:/\.less$/i,
                use: getStyleLoaders("less-loader"),
            },

处理图片

npm i image-minimizer-webpack-plugin imagemin
无损压缩 
npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo -D
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 小于10kb的图片会被转为base64处理
          },
        },
      },
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");//压缩图片

  optimization: {
    minimizer: [
      // 压缩图片
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },

这里也可以不做图片的压缩配置,自己手动压缩图片

压缩css并提取css成单独文件

npm i css-minimizer-webpack-plugin mini-css-extract-plugin -D
const MiniCssExtractPlugin = require("mini-css-extract-plugin");//将css代码单独打包
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");//css压缩

//提取css成单独文件
const getStyleLoaders = (pre) => {
  return [
    MiniCssExtractPlugin.loader,//修改
    "css-loader",
    {
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: [
            "postcss-preset-env",
          ],
        },
      },
    },
    pre
  ].filter(Boolean);
};
 压缩css
 new MiniCssExtractPlugin({
      filename: 'static/css/[name].[contenthash:10].css',
      chunkFilename: 'static/css/[name].[contenthash:10].chunk.css'
    }),

    minimizer: [
      new CssMinimizerPlugin(),//css压缩
      new TerserWebpackPlugin(),//js压缩 因为css压缩了不压缩代码会有问题
      new ImageMinimizerPlugin({
    ...
      }),
]

配置eslint 和babel处理js文件

npm i babel-loader eslint-webpack-plugin  eslint eslint-webpack-plugin eslint-plugin-vue

创建.eslintrc.js和babel.config.js

eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: ["plugin:vue/vue3-essential", "eslint:recommended"],
  parserOptions: {
    parser: "@babel/eslint-parser",
  },
};

babel.config.js

module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"],
};
      {
        test: /\.(jsx|js)$/,
        include: path.resolve(__dirname, "../src"),
        loader: "babel-loader",
        options: {
          cacheDirectory: true,
          cacheCompression: false,
        },
      },
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
    new ESLintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),处理src文件夹中的内容
      exclude: "node_modules",//不处理node_modules文件夹中的内容
      //开启缓存
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"//缓存文件路径
      ),
    }),

环境变量处理

npm i cross-env
// 需要通过 cross-env 定义环境变量 获取环境变量

const isProduction = process.env.NODE_ENV === "production";

packjson.js

  "scripts": {
    "start": "npm run dev",
//开发模式
    "dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.config.js",
//生产模式
    "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js"
  },

webpack.config.js

// 需要通过 cross-env 定义环境变量 获取环境变量
const isProduction = process.env.NODE_ENV === "production";
const { DefinePlugin } = require("webpack");

    //定义环境变量
    //cross-eny定义的环境变量给webpack打包工具使用
    //DefinePlugin 定义的环境变量才是给源代码使用的 从而解决vue3页面警告的问题
    new DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false

    }),

处理图标

在index中引入

<!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">
  <link rel="short icon" href="favicon.ico">
  <title>reactcli</title>
</head>

<body>
  <div id="app"></div>
</body>

</html>

这还不能实现效果,因为webpack只打包了src下的文件,index.html所处的public文件不会处理,

单纯只是引入找不到public下的图标文件

通过copyplugin处理

const CopyPlugin = require("copy-webpack-plugin");//webpack没有处理public文件夹下文件 所有我们直接复制过去

    // 将public下面的资源复制到dist目录去(除了index.html)
  new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          toType: "dir",
          noErrorOnMissing: true, // 不生成错误
          globOptions: {
            // 忽略文件
            ignore: ["**/index.html"],
          },
          info: {
            // 跳过terser压缩js
            minimized: true,
          },
        },
      ],
    }),
  ].filter(Boolean)

根据环境变量配置开发模式和生产模式下配置

// webpack.config.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const CopyPlugin = require("copy-webpack-plugin");

// 需要通过 cross-env 定义环境变量
const isProduction = process.env.NODE_ENV === "production";

const getStyleLoaders = (preProcessor) => {
  return [
    isProduction ? MiniCssExtractPlugin.loader : "vue-style-loader",
    "css-loader",
    {
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],
        },
      },
    },
    preProcessor,
  ].filter(Boolean);
};

module.exports = {
  entry: "./src/main.js",
  output: {
    path: isProduction ? path.resolve(__dirname, "../dist") : undefined,
    filename: isProduction
      ? "static/js/[name].[contenthash:10].js"
      : "static/js/[name].js",
    chunkFilename: isProduction
      ? "static/js/[name].[contenthash:10].chunk.js"
      : "static/js/[name].chunk.js",
    assetModuleFilename: "static/js/[hash:10][ext][query]",
    clean: true,
  },
  module: {
    rules: [
      {
        // 用来匹配 .css 结尾的文件
        test: /\.css$/,
        // use 数组里面 Loader 执行顺序是从右到左
        use: getStyleLoaders(),
      },
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
          },
        },
      },
      {
        test: /\.(ttf|woff2?)$/,
        type: "asset/resource",
      },
      {
        test: /\.(jsx|js)$/,
        include: path.resolve(__dirname, "../src"),
        loader: "babel-loader",
        options: {
          cacheDirectory: true,
          cacheCompression: false,
          plugins: [
            // "@babel/plugin-transform-runtime" // presets中包含了
          ],
        },
      },
      // vue-loader不支持oneOf
      {
        test: /\.vue$/,
        loader: "vue-loader", // 内部会给vue文件注入HMR功能代码
        options: {
          // 开启缓存
          cacheDirectory: path.resolve(
            __dirname,
            "node_modules/.cache/vue-loader"
          ),
        },
      },
    ],
  },
  plugins: [
    new ESLintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: "node_modules",
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          toType: "dir",
          noErrorOnMissing: true,
          globOptions: {
            ignore: ["**/index.html"],
          },
          info: {
            minimized: true,
          },
        },
      ],
    }),
    isProduction &&
      new MiniCssExtractPlugin({
        filename: "static/css/[name].[contenthash:10].css",
        chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
      }),
    new VueLoaderPlugin(),
    new DefinePlugin({
      __VUE_OPTIONS_API__: "true",
      __VUE_PROD_DEVTOOLS__: "false",
    }),
  ].filter(Boolean),
  optimization: {
    minimize: isProduction,
    // 压缩的操作
    minimizer: [
      new CssMinimizerPlugin(),
      new TerserWebpackPlugin(),
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
    splitChunks: {
      chunks: "all",
    },
    runtimeChunk: {
      name: (entrypoint) => `runtime~${entrypoint.name}`,
    },
  },
  resolve: {
    extensions: [".vue", ".js", ".json"],
  },
  devServer: {
    open: true,
    host: "localhost",
    port: 3000,
    hot: true,
    compress: true,
    historyApiFallback: true, // 解决vue-router刷新404问题
  },
  mode: isProduction ? "production" : "development",
  devtool: isProduction ? "source-map" : "cheap-module-source-map",
};

vue的全家桶配置

vue-router

npm i vue-router


在src文件下创建一个 router 文件夹,里边创建一个index.js

import { createRouter,createWebHistory } from 'vue-router'
import index from './components/index.vue'
import login from './components/login.vue'
const routerHistory = createWebHistory()
const routes = [
    {
        path:'/',
        name:'index',
        component:index
    }, 
    {
        path:'/login',
        name:'login',
        component:login
    }
]
const router = createRouter({
    history: routerHistory,
    routes
})
export default router



在main.js中引入router

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './index.css'
const app = createApp(App);
app.use(router);
app.mount('#app')


vuex


安装 vuex

npm i vuex


在src文件下创建一个 store 文件夹,里边创建一个index.js

//  准备引入 vuex
import { createStore } from 'vuex'
 
const store = createStore({
    // state:{},
    state(){},
    mutations:{},
    getters:{},
    actions:{},
    modules:{}
})
export default store


在main.js中引入veux


import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

// 挂载 
createApp(App).use(router).mount('#app')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值