vue3搭建脚手架实战

我们现在来根据官方提供的基础的脚手架搭建一个完整vue-cli

这里采用vite,至于优势就不用我多说了吧,像传统的webpack采用的是通过entry入口文件把所有项目用到的模块进行打包编译,有时候启动一个项目就要几十秒钟,更新文件也非常的慢。

而vite从本质上讲,是让浏览器接管捆绑器的部分工作:Vite只需要根据浏览器的要求按需转换和提供源代码即可,这就让其速度体验上获得了巨大的飞跃。具体的介绍配置可以去看一下官网-----》vite官网

废话不多说,首先我们用官方提供的简易的脚手架搭建(主要是稍微快一点,其实也是个最简易版的,只有vue和vite两个依赖,和基本的文件目录,方便我们自由发挥配置)

1.拉取最基础的脚手架

$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev

搭建完成基本上就是这么一个目录

然后我们想加入typeScript+scss+vuex+vue-router+eslint来集成一个完整的脚手架

2.安装需要的资源依赖包

推荐用yarn去搞,npm太慢。。。

安装vue基础配置

yarn add axios sass vue-router vuex@4.0.0-rc.2 typescript -D

安装eslint等格式化工具 

yarn add prettier eslint-plugin-vue eslint-plugin-prettier eslint-config-prettier eslint @typescript-eslint/eslint-plugin@4.14.2 @typescript-eslint/parser@4.14.2 -D

安装配置环境变量需要依赖

yarn add cross-env -D

 3.配置项目

  • 配置ts

根目录下加tsconfig.json,shim.d.ts

shim.d.ts

declare module '*.vue' {
    import { Component } from 'vue'
    const component: Component
    export default component
}

declare module '/@/*'

tsconfig.json

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "ESNEXT",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "ESNext",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    "paths": {
      "@/":["./src"]
    },                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

 

  • 根目录下建立 vite.config.ts,类似在webpack中配置你的vue.config.js
const path = require('path')
module.exports = {
    /**
     * 在生产中服务时的基本公共路径。
     * @default '/'
     */
    base: '/huangbiao',
    /**
     * 与“根”相关的目录,构建输出将放在其中。如果目录存在,它将在构建之前被删除。
     * @default 'dist'
     */
    outDir: 'target',
    port: 3000,
    // 是否自动在浏览器打开
    open: true,
    // 是否开启 https
    https: false,
    // 服务端渲染
    ssr: false,
    // 引入第三方的配置
    optimizeDeps: {
        include: ['moment', 'echarts', 'axios', 'mockjs']
    },
    alias: {
        '/@/': path.resolve(__dirname, 'src')
        // '/@components/': path.resolve(__dirname, './src/components')
    },
    proxy: {
        // 如果是 /lsbdb 打头,则访问地址如下
        '/lsbdb': 'http://10.192.195.96:8087'
        // 如果是 /lsbdb 打头,则访问地址如下
        // '/lsbdb': {
        //   target: 'http://10.192.195.96:8087/',
        //   changeOrigin: true,
        //   // rewrite: path => path.replace(/^\/lsbdb/, '')
        // }
    }
}
  • 接着在src下建立几个简单的vue文件

 

  • 然后,配置router

在src文件夹下建立router文件夹,并且建立一个index文件,和一个routes文件

index.ts

import { createRouter, createWebHashHistory } from 'vue-router'
import Routes from './routes'
export default createRouter({
	history: createWebHashHistory(),
	routes: Routes
})

routes.ts

注意/@/已经在vite.config.ts做过配置,代表src路径

const Home = () => import('/@/pages/home/index.vue')
const About = () => import('/@/pages/about.vue')
const My = () => import('/@/pages/my.vue')

export default [
	{
		path: '/',
		redirect: '/home'
	},
	{
		path: '/home',
		name: 'home',
		component: Home
	},
	{
		path: '/About',
		name: 'About',
		component: About
	},
	{
		path: '/My',
		name: 'My',
		component: My
	}
]

在main.js中引入

import router from './router/index'
const app = createApp(App)
app.use(router)
app.mount('#app')
  • 配置store,在src下建立store文件夹,这里只随便简单写一个简单的

index.ts

注意是createStore!

import { createStore } from 'vuex'
interface State {
	name: string
}

export default createStore({
	state: <State>{
		name: 'hello word!'
	}
})

main.ts

import store from './store/index'
const app = createApp(App)
app.use(store)
app.mount('#app')

以上简单的vue3+router+vuex就算是完成了。

接着封装一个http请求

因为我一直倡导的是请求要统一封装,方便维护升级接口迁移,在vue2中,我们一直走的是this.$api.login()的形式,接下来我们看看在三里面怎么做。

main.ts中全局挂载请求方法

import { getApi } from './utils/common'
app.config.globalProperties.$api = getApi

./utils/common.ts

/**
 *
 * @param {*} key url 接口
 * @param {*} data 传输的数据
 */
export const getApi = async function (key: string, data: any = {}) {
	const res = await import('/@/http/index')
	return res.default[key](data)
}

api.ts

export default {
	Login: {
		//登陆 换取token
		url: '/login'
	},
	HomePageList: {
		//获取商城首页数据
		url: '/mall/homepage/detail',
		header: {
			'Content-Type': 'application/json', //可省略默认
			isIgnore: true //是否过滤拦截,默认false
		}
	}
}

调用场景

import {  getCurrentInstance } from 'vue'
export default {
    setup(props: Object, context: Object) {
			const { ctx }: any = getCurrentInstance()
			console.log(ctx.$api)
			//请求案例
			ctx.$api('Login', { name: 222 }).then((res: object) => {
				console.log(res)
			})
    }
}
  • 最后还差一个eslint和prettier美化代码

根目录下添加

prettier.config.js

module.exports = {
    printWidth: 120,
    tabWidth: 4,
    useTabs: true,
    bracketSpacing: true,   // 是否在对象属性添加空格
    semi: false, // 未尾逗号
    vueIndentScriptAndStyle: true,
    singleQuote: true, // 单引号
    quoteProps: 'as-needed',
    bracketSpacing: true,
    trailingComma: 'none', // 未尾分号
    jsxBracketSameLine: false,
    jsxSingleQuote: false,
    arrowParens: 'always',
    insertPragma: false,
    requirePragma: false,
    proseWrap: 'never',
    htmlWhitespaceSensitivity: 'strict',
    // endOfLine: 'auto',
}

.eslintrc.js

module.exports = {
    parser: 'vue-eslint-parser',
    parserOptions: {
        parser: '@typescript-eslint/parser',
        eslintIntegration: true,
        ecmaVersion: 2021,
        sourceType: 'module',
        ecmaFeatures: {
            jsx: true
        }
    },
    extends: [
        'plugin:vue/vue3-recommended',
        'plugin:@typescript-eslint/recommended',
        'prettier/@typescript-eslint',
        'plugin:prettier/recommended'
    ],
    rules: {
        'vue/singleline-html-element-content-newline': [
            'error',
            {
                ignoreWhenNoAttributes: true,
                ignoreWhenEmpty: true,
                ignores: ['pre', 'textarea', 'button']
            }
        ],
        '@typescript-eslint/ban-ts-ignore': 'off',
        '@typescript-eslint/explicit-function-return-type': 'off',
        '@typescript-eslint/no-explicit-any': 'off',
        '@typescript-eslint/no-var-requires': 'off',
        '@typescript-eslint/no-empty-function': 'off',
        'vue/custom-event-name-casing': 'off',
        "prettier/prettier":'off',
        'vue/singleline-html-element-content-newline':'off',//闭合标签换行
        'vue/max-attributes-per-line':'off',//属性要求换行
        'vue/html-closing-bracket-newline':'off',
        'vue/html-indent': 'off',
        'no-use-before-define': 'off',
        // 'no-use-before-define': [
        //   'error',
        //   {
        //     functions: false,
        //     classes: true,
        //   },
        // ],
        '@typescript-eslint/no-use-before-define': 'off',
        // '@typescript-eslint/no-use-before-define': [
        //   'error',
        //   {
        //     functions: false,
        //     classes: true,
        //   },
        // ],
        '@typescript-eslint/ban-ts-comment': 'off',
        '@typescript-eslint/ban-types': 'off',
        '@typescript-eslint/no-non-null-assertion': 'off',
        '@typescript-eslint/explicit-module-boundary-types': 'off',
        '@typescript-eslint/no-unused-vars': [
            'error',
            {
                argsIgnorePattern: '^h$',
                varsIgnorePattern: '^h$'
            }
        ],
        'no-unused-vars': [
            'error',
            {
                argsIgnorePattern: '^h$',
                varsIgnorePattern: '^h$'
            }
        ],
        'space-before-function-paren': 'off',
        quotes: ['error', 'single'],
        'comma-dangle': ['error', 'never']
    }
}

在pagckage.json中添加命令

"scripts": {
    "dev": "vite",
    "build:test": "cross-env NODE_ENV=test vite build",
    "build:master": "cross-env NODE_ENV=master vite build",
    "lint": "eslint --fix --ext .js,.ts,.vue src/",
    "format": "prettier --write  \"src/**/*.scss\" \"src/**/*.ts\" \"src/**/*.vue\""
  },

环境变量区分,build:test和build:master,可通过以下区分

process.env.NODE_ENV

 

以上便是一个完整脚手架的全部配置了,你也可以把eslint加入到githook,看你自己怎么玩了。此外我这里还有上述所有代码的完整地址,还有定义组件,引入element-plus组件库的使用等等。 
点击前往

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue-cli脚手架Vue官方提供的一个工具,用于快速生成一个Vue项目的模板。它预先定义了项目的目录结构和基础代码,可以帮助开发者更快速地搭建一个Vue项目的框架。通过Vue-cli,开发者可以使用简单的命令完成项目环境的搭建,包括插件、开发服务、构建打包等功能。安装Vue-cli可以通过命令npm install -g vue-cli来进行。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [Vue-cli脚手架](https://blog.csdn.net/qq_42265394/article/details/119778843)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Vue-cli(vue脚手架)超详细教程](https://blog.csdn.net/u012660464/article/details/114834812)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Vue实战Vue CLI 脚手架](https://blog.csdn.net/weixin_45442617/article/details/113951338)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

槿畔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值