Vue CLI and project构建

深入LearningVue CLI installation, configuration and using, MasterVueproject creation, Development, 构建 and deployment流程

1. Vue CLIoverview

Vue CLI is Vue.js 官方commands行tool, 它providing了一套完整 脚手架, 用于 fast 速creation, Development and 构建Vueproject.

1.1 Vue CLI corefunctions

  • project初始化: fast 速creationVueproject, support many 种预设 and 自定义configuration
  • Developmentserver: providing热重载, errorchecketc.functions Developmentserver
  • 构建tool: 将project打package for produceversion, package含code压缩, optimizationetc.functions
  • 插件system: supportinstallation and configuration各种插件, scaleprojectfunctions
  • configurationmanagement: providingflexible configuration方式, supportenvironmentvariable, proxy设置etc.

1.2 Vue CLI and Vite

Vue CLI基于Webpack构建, 而Vite is Vue团队推出 new 一代 before 端构建tool, 具 has 更 fast Developmentserver启动速度 and 热update速度. for 于 new project, 推荐usingVite, 而 for 于现 has Vue CLIproject, 可以继续using or 考虑migration to Vite.

2. installationVue CLI

in installationVue CLI之 before , 需要确保已经installation了Node.js (推荐version14.x or 更 high ) and npm.

2.1 installationNode.js and npm

可以 from Node.js官网 under 载并installationNode.js, npm会随Node.js一起installation.

installationcompletion after , 可以through以 under commandscheckversion:

node -v
npm -v

2.2 installationVue CLI

可以usingnpm or yarn全局installationVue CLI:

# usingnpminstallation
npm install -g @vue/cli

# usingyarninstallation
yarn global add @vue/cli

installationcompletion after , 可以through以 under commandscheckversion:

vue --version

3. creationVueproject

usingVue CLIcreation一个 new Vueproject.

3.1 usingvue createcommands

vue create my-vue-project

执行该commands after , 会提示选择预设:

  • Default ([Vue 3] babel, eslint): 默认预设, usingVue 3 and basicconfiguration
  • Default ([Vue 2] babel, eslint): 默认预设, usingVue 2 and basicconfiguration
  • Manually select features: 手动选择functions

3.2 手动选择functions

such as果选择"Manually select features", 可以选择以 under functions:

  • Choose Vue version: 选择Vueversion
  • Babel: usingBabel转译JavaScriptcode
  • TypeScript: usingTypeScript
  • Progressive Web App (PWA) Support: supportPWA
  • Router: installationVue Router
  • Vuex: installationVuex
  • CSS Pre-processors: usingCSS预processing器 (such asSass/Less)
  • Linter / Formatter: usingcodecheck and formattool
  • Unit Testing: using单元testtool
  • E2E Testing: using端 to 端testtool

3.3 usinggraph形化界面creationproject

Vue CLI还providing了graph形化界面, 可以through以 under commands启动:

vue ui

然 after in 浏览器in打开http://localhost:8000, usinggraph形化界面creation and managementVueproject.

4. projectstructure

creationcompletion after , Vueproject basicstructuresuch as under :

my-vue-project/
├── node_modules/          # 依赖package
├── public/               # 静态resource
│   ├── favicon.ico       # 网站graph标
│   └── index.html        # HTML模板
├── src/                  # sourcescode
│   ├── assets/           # resourcefile (graph片, 字体etc.) 
│   ├── components/       # component
│   ├── router/           # routingconfiguration
│   ├── store/            # Vuexstatusmanagement
│   ├── views/            # 视graphcomponent
│   ├── App.vue           # 根component
│   └── main.js           # 入口file
├── .gitignore            # Gitignorefile
├── babel.config.js       # Babelconfiguration
├── package.json          # projectconfiguration and 依赖
├── README.md             # project说明
└── vue.config.js         # Vue CLIconfiguration

5. Development流程

让我们开始DevelopmentVueproject.

5.1 启动Developmentserver

进入projectTable of Contents, 执行以 under commands启动Developmentserver:

cd my-vue-project
npm run serve

Developmentserver启动 after , 可以 in 浏览器in访问http://localhost:8080查看project.

5.2 Developmentserverfunctions

  • 热重载: modifycode after , 浏览器会自动刷 new , 无需手动刷 new
  • errorcheck: 实时显示语法error and warning
  • networkrequestproxy: 可以configurationproxy, 解决跨域issues
  • HTTPSsupport: 可以启用HTTPS, 用于test需要HTTPS functions

5.3 creationcomponent

in src/componentsTable of Contents under creation一个 new component, 例such asHelloWorld.vue:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="count++">点击次数: {{ count }}</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: {
      type: String,
      default: 'Hello Vue!'
    }
  },
  data() {
    return {
      count: 0
    };
  }
}
</script>

<style scoped>
.hello {
  text-align: center;
  padding: 20px;
}

button {
  background-color: #4285F4;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #3367D6;
}
</style>

5.4 in App.vueinusingcomponent

<template>
  <div id="app">
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

6. configurationVueproject

可以throughvue.config.jsfileconfigurationVueproject.

6.1 basicconfiguration

// vue.config.js
module.exports = {
  // projectdeployment Basicspath
  publicPath: process.env.NODE_ENV === 'production' ? '/my-app/' : '/',
  
  // produceenvironment构建file Table of Contents
  outputDir: 'dist',
  
  // 放置生成 静态resource Table of Contents
  assetsDir: 'assets',
  
  // 生成 index.html 输出path
  indexPath: 'index.html',
  
  // file名哈希
  filenameHashing: true,
  
  //  is 否 in Developmentenvironment under througheslint-loader in 每次保存时lintcode
  lintOnSave: process.env.NODE_ENV !== 'production',
  
  //  is 否usingpackage含run时编译器 Vue构建version
  runtimeCompiler: false,
  
  // produceenvironment is 否生成sourceMapfile
  productionSourceMap: false
}

6.2 Developmentserverconfiguration

// vue.config.js
module.exports = {
  devServer: {
    // Developmentserver端口
    port: 8080,
    
    //  is 否自动打开浏览器
    open: true,
    
    // 启用HTTPS
    https: false,
    
    // networkrequestproxyconfiguration
    proxy: {
      '/api': {
        target: 'http://localhost:3000', // 目标server地址
        ws: true, // supportWebSocket
        changeOrigin: true, // 改变requestsources
        pathRewrite: {
          '^/api': '' // 重写path
        }
      }
    }
  }
}

6.3 CSSconfiguration

// vue.config.js
module.exports = {
  css: {
    //  is 否usingcss分离插件ExtractTextPlugin
    extract: process.env.NODE_ENV === 'production',
    
    //  is 否开启CSS source maps
    sourceMap: false,
    
    // CSS预设器configuration项
    loaderOptions: {
      sass: {
        prependData: `@import "@/assets/styles/variables.scss";`
      }
    },
    
    //  is 否启用CSS modules
    requireModuleExtension: true
  }
}

6.4 插件configuration

// vue.config.js
const webpack = require('webpack')

module.exports = {
  configureWebpack: {
    plugins: [
      // 定义全局variable
      new webpack.DefinePlugin({
        'process.env': {
          VUE_APP_VERSION: JSON.stringify('1.0.0'),
          VUE_APP_BASE_URL: JSON.stringify('http://api.example.com')
        }
      })
    ]
  }
}

7. 构建 and deployment

Developmentcompletion after , 需要构建project并deployment to produceenvironment.

7.1 构建project

执行以 under commands构建project:

npm run build

构建completion after , 生成 file会存放 in distTable of Contentsin.

7.2 deploymentproject

可以将distTable of Contentsin filedeployment to 任何静态fileserver on , 例such as:

  • Nginx
  • Apache
  • GitHub Pages
  • Vercel
  • Netlify
  • 阿里云OSS
  • 腾讯云COS

7.3 Nginxconfigurationexample

server {
    listen 80;
    server_name example.com;
    root /path/to/your/dist;
    index index.html;
    
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

8. usingVitecreationVueproject

for 于 new project, 推荐usingVitecreationVueproject, 它具 has 更 fast Developmentserver启动速度 and 热update速度.

8.1 usingnpmcreationViteproject

# usingnpmcreationVue 3project
npm create vite@latest my-vue-app -- --template vue

# usingnpmcreationVue 3 + TypeScriptproject
npm create vite@latest my-vue-app -- --template vue-ts

8.2 usingyarncreationViteproject

# usingyarncreationVue 3project
yarn create vite my-vue-app --template vue

# usingyarncreationVue 3 + TypeScriptproject
yarn create vite my-vue-app --template vue-ts

8.3 Viteprojectstructure

my-vue-app/
├── node_modules/          # 依赖package
├── public/               # 静态resource
│   └── vite.svg          # Vitegraph标
├── src/                  # sourcescode
│   ├── assets/           # resourcefile
│   ├── components/       # component
│   ├── App.vue           # 根component
│   ├── main.js           # 入口file
│   └── style.css         # 全局样式
├── .gitignore            # Gitignorefile
├── index.html            # HTML模板
├── package.json          # projectconfiguration and 依赖
├── README.md             # project说明
├── vite.config.js        # Viteconfiguration
└── yarn.lock             # Yarn依赖lockfile

8.4 Viteconfigurationexample

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  // 插件configuration
  plugins: [vue()],
  
  // serverconfiguration
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  
  // 构建configuration
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    minify: 'terser',
    rollupOptions: {
      output: {
        manualChunks: {
          'vue-vendor': ['vue', 'vue-router', 'vuex'],
          'ui-vendor': ['element-plus']
        }
      }
    }
  }
})

9. 常用插件

可以installation各种插件scaleVueproject functions.

9.1 Vue Router

routingmanagement插件:

npm install vue-router@4

9.2 Vuex/Pinia

statusmanagement插件:

# Vuex
npm install vuex@4

# Pinia (Vue 3推荐) 
npm install pinia

9.3 CSS预processing器

CSS预processing器:

# Sass/SCSS
npm install sass

# Less
npm install less

# Stylus
npm install stylus

9.4 UIcomponentlibrary

常用 UIcomponentlibrary:

  • Element Plus (Vue 3) : npm install element-plus
  • Ant Design Vue: npm install ant-design-vue
  • Vuetify: npm install vuetify
  • BootstrapVue: npm install bootstrap-vue bootstrap

9.5 HTTP客户端

HTTP客户端library:

# Axios
npm install axios

10. best practices

10.1 projectstructurebest practices

  • 按functions or module组织filestructure
  • using清晰 命名规范, such askebab-case or PascalCase
  • 将component拆分 for 原子component and 复合component
  • usingassetsTable of Contents存放静态resource
  • usingviewsTable of Contents存放页面component

10.2 Developmentbest practices

  • usingESLint and Prettier规范code风格
  • usingTypeScriptimprovingcodequality and 可maintenance性
  • writing单元test and 集成test
  • usinggitforversion控制, 遵循Git Flow or GitHub Flow
  • usingenvironmentvariablemanagement不同environment configuration

10.3 构建 and deploymentbest practices

  • usingCI/CDautomation构建 and deployment流程
  • configuration适当 cache策略, improving页面加载速度
  • usingCDN加速静态resource加载
  • configurationHTTPS, improving网站security性
  • monitor网站performance and error, 及时发现 and 解决issues

11. Vue CLIprojectmigration to Vite

such as果想将现 has Vue CLIprojectmigration to Vite, 可以按照以 under 步骤for:

  1. creationvite.config.jsfile, configurationVite
  2. updatepackage.json, modifyscripts and 依赖
  3. 将publicTable of Contents under index.htmlmove to project根Table of Contents
  4. updateindex.html, 添加Vite scripttag
  5. 调整importpath, 确保符合Vite 要求
  6. testproject, 确保functions正常

练习 1: installationVue CLI并creationproject

  1. installationNode.js and npm.
  2. 全局installationVue CLI.
  3. usingVue CLIcreation一个 new Vueproject.
  4. 启动Developmentserver, 查看project.

练习 2: creationcomponent并using

  1. in projectincreation一个 new component.
  2. in App.vueinusing该component.
  3. 添加component 样式 and 交互functions.
  4. testcomponent functions.

练习 3: configurationVueproject

  1. creationvue.config.jsfile.
  2. configurationDevelopmentserver端口 and proxy.
  3. configurationCSS预processing器.
  4. 构建project, 查看构建结果.

练习 4: usingVitecreationproject

  1. usingVitecreation一个 new Vueproject.
  2. 比较Viteproject and Vue CLIproject structurediff.
  3. 启动Developmentserver, 体验Vite 热update速度.