从零开始使用 Webpack 搭建 Vue3 开发环境

从零开始使用 Webpack 搭建 Vue3 开发环境

前情提要

创建项目

首先需要创建一个空目录,在该目录打开命令行,执行 npm init -y 命令创建一个项目,完成后会自动生成一个 package.json 文件

添加一个 Webpack 配置文件

project

  project-name
+ |- index.html
  |- package.json
+ |- webpack.config.js
+ |- /src
+   |- index.js

webpack.config.js

'use strict'

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist'),
    assetModuleFilename: 'images/[name][ext]'
  },
  resolve: {
    alias: {
      '@': path.join(__dirname, 'src')
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: [
          {
            loader: 'vue-loader'
          }
        ]
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader'
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        type: 'asset/resource'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './index.html'
    }),
    new VueLoaderPlugin()
  ],
  devServer: {
    compress: true,
    port: 8088
  }
}

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>这是标题</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

安装依赖

npm install --save-dev css-loader html-webpack-plugin style-loader vue-loader @vue/compiler-sfc webpack webpack-cli webpack-dev-server

需要注意的几个点

  • VueLoaderPlugin 的导入方式改变了
  • vue-loader@next 当前需要自行指定版本
  • 新增了 @vue/compiler-sfc 替换原来的 vue-template-compiler
  • 其它 Webpack 基本配置仅仅配置了样式表和图像的加载

启动本地服务

在 package.json 文件对应的 scripts 处新增命令

package.json

{
  "scripts": {
    "dev": "webpack serve"
  }
}

执行 npm run dev 访问 localhost:8088,如果此步骤执行不成功,可以先执行下一步

Vue

npm install --save vue vue-router vuex

当前均需要自行指定版本

根组件

project

  project-name
  |- package.json
  |- /src
+   |- app.vue

app.vue

<template>
  <ul>
    <li><router-link to="/">Home</router-link></li>
    <li><router-link to="/about">About</router-link></li>
  </ul>
  <router-view/>
</template>
  • Vue3 组件的根元素可以允许为多个
  • <router-view> 是 vue-router 定义的容器组件

入口文件

src/index.js

import { createApp } from 'vue'

import App from '@/app.vue'
import router from '@/router'
import store from '@/store'

createApp(App)
  .use(router)
  .use(store)
  .mount('#app')

不同于 Vue2 的整包导入方式,Vue3 采用了按需导入的方式,比如这里只导入了 createApp 这个方法,这样做的好处是可以支持 Webpack 的 treeshaking, 其它没有用到的部分将不会出现在最终打包文件中

createApp 方法创建了一个实例,额外的东西(router, store 等)均挂载到这个实例上,这样做的好处是不会影响到另外创建的其它实例

Vue3 的响应式系统使用了 ES2015 的 Proxy (代理),其浏览器兼容性参考 CanIUse,该特性无法兼容旧浏览器

Router

project

  project-name
  |- package.json
  |- /src
+   |- /router
+     |- index.js

src/router/index.js

import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    component: require('@/views/index.vue').default
  },
  {
    path: '/about',
    component: require('@/views/about.vue').default
  },
  {
    path: '/:catchAll(.*)',
    component: require('@/views/404.vue').default
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router
  • 导入方式也是按需导入
  • 原来的 mode 参数变为 history
  • 路由方式除了 createWebHashHistory,还有 createWebHistory 和 createMemoryHistory
  • 路由未匹配时使用 '/:catchAll(.*)'

创建页面组件

project

  project-name
  |- package.json
  |- /src
+   |- /views
+     |- 404.vue
+     |- about.vue
+     |- index.vue

index.vue

<template>
  <h1>Index</h1>
</template>

在组件中使用 router

import { useRouter } from 'vue-router'

export default {
  setup() {
    const router = useRouter()

    // 也可以解构
    const { push, go, back } = useRouter()
  }
}
  • router 就是原来实例的 $router,也有 beforeEach, afterEach 等等方法

在组件中使用 route

import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()
  }
}
  • route 是个响应式的代理对象,和原来实例的 $route 一样,也有 query, params 等属性
  • 不建议将 route 解构,解构后的 query, params 并不是响应式的

Store

project

  project-name
  |- package.json
  |- /src
+   |- /store
+     |- index.js

该文件创建并导出一个 Vuex 实例

src/store/index.js

import { createStore } from 'vuex'

const store = createStore({
  state: {},
  getters: {},
  mutations: {},
  actions: {}
})

export default store
  • 导入方式也为按需导入
  • 其它照旧,没有什么变化

在组件中使用 store

import { useStore } from 'vuex'

export default {
  setup() {
    const { state, getters, commit, dispatch } = useStore()

    return {
      state
    }
  }
}

state 是响应式的代理对象,不通过 commit 提交 mutations 而是直接修改 state 也是可以的,控制台并没有给出什么警告

NPM Scripts

在 package.json 文件对应的 scripts 处新增命令

package.json

{
  "scripts": {
    "dev": "webpack serve",
    "build": "webpack"
  }
}

更多

posted @ 2020-07-09 12:34  by.Genesis  阅读(8432)  评论(1编辑  收藏  举报