从零开始使用 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@next @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@next vue-router@next vuex@next

当前均需要自行指定版本

根组件

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>
  • 组件的根元素可以允许为多个
  • <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.0 的整包导入方式,Vue3.0 采用了按需导入的方式,比如这里只导入了 createApp 这个方法,这样做的好处是可以支持 Webpack 的 treeshaking, 其它没有用到的部分将不会出现在最终打包文件中

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

Vue3.0 的响应式系统使用了 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"
  }
}

更多

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对于使用Webpack搭建Vue2项目,你可以按照以下步骤进行操作: 1. 确保你已经安装了Node.js和npm。你可以在终端中运行以下命令来验证它们是否已安装: ``` node -v npm -v ``` 如果没有安装,可以前往 Node.js 官方网站(https://nodejs.org/)下载并安装最新的稳定版本。 2. 创建一个新目录,作为你的项目根目录,并进入该目录。 3. 初始化一个新的npm项目,运行以下命令并按照提示进行操作: ``` npm init ``` 4. 在项目根目录下安装所需的依赖,包括VueVue Loader、Vue Router等。运行以下命令: ``` npm install vue@2 vue-loader@15 vue-router@3 webpack webpack-cli --save-dev ``` 5. 在项目根目录下创建一个`webpack.config.js`文件,并配置Webpack的基本设置。可以参考以下示例: ```javascript const path = require('path'); module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, }, ], }, resolve: { alias: { vue$: 'vue/dist/vue.esm.js', }, extensions: ['*', '.js', '.vue', '.json'], }, }; ``` 6. 在项目根目录下创建一个`src`目录,并在其中创建一个`main.js`文件作为Vue应用的入口文件。 7. 在`src`目录下创建一个`components`目录,并在其中创建你的Vue组件。 8. 创建一个简单的Vue组件,并在`main.js`中引入该组件: ```javascript import Vue from 'vue'; import App from './components/App.vue'; new Vue({ render: (h) => h(App), }).$mount('#app'); ``` 9. 创建一个HTML文件作为你的应用的模板,例如`index.html`: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue App</title> </head> <body> <div id="app"></div> <script src="dist/bundle.js"></script> </body> </html> ``` 10. 在`package.json`文件中添加以下脚本命令: ```json "scripts": { "build": "webpack" } ``` 这将允许你在终端中运行`npm run build`命令来构建你的Vue项目。 11. 运行以下命令来构建和打包你的Vue项目: ``` npm run build ``` 这将生成一个`dist`目录,并将打包后的Vue应用文件输出到其中。 12. 打开你的HTML文件,

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值