Table of Contents
2. 在项目根目录下, 创建 .env.prod 文件 (生产环境变量)
3. 在项目根目录下, 创建 deploy/products.js 文件
图解
Home Web Front-end JS Tutorial Introduction to the method of automatically deploying projects to the server with Vue-CLI 3.x (code)

Introduction to the method of automatically deploying projects to the server with Vue-CLI 3.x (code)

Apr 02, 2019 am 11:09 AM
javascript linux vue.js server

本篇文章给大家带来的内容是关于Vue-CLI 3.x 自动部署项目至服务器的方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

前言:平时部署前端项目流程是:先部署到测试环境ok后再发布到生产环境上,部署到测试环境用 xshell 连上服务器,然后用 xftp 连接服务器,然后本地 build 项目,接着把 build 好的文件通过 xftp 上传到服务器上,整个流程感觉稍有繁琐,重复。

本教程讲解的是 Vue-CLI 3.x 脚手架搭建的vue项目, 利用scp2自动化部署到静态文件服务器 Nginx

一  安装scp2

scp2是一个基于ssh2增强实现,纯粹使用JavaScript编写。
而ssh2就是一个使用nodejs对于SSH2的模拟实现。scp,是secure copy的缩写, scp是Linux系统下基于SSH登陆进行安全的远程文件拷贝命令。这里我们就用这个功能,在Vue编译构建成功之后,将项目推送至测试/生产环境,以方便测试,提高效率。
安装scp2:

npm install scp2 --save-dev
Copy after login

二、配置测试/生产环境 服务器SSH远程登陆账号信息

1. 在项目根目录下, 创建 .env.dev 文件 (测试环境变量)

VUE_APP_SERVER_ID变量表示 当前需部署的测试服务器ID为0

// .env.dev文件中
VUE_APP_SERVER_ID=0
Copy after login

2. 在项目根目录下, 创建 .env.prod 文件 (生产环境变量)

VUE_APP_SERVER_ID变量表示 当前需部署的生产服务器ID为1

// .env.prod文件中
VUE_APP_SERVER_ID=1
Copy after login

3. 在项目根目录下, 创建 deploy/products.js 文件

/*
 *读取env环境变量
 */
const fs = require('fs');
const path = require('path');
// env 文件 判断打包环境指定对应的服务器id
const envfile = process.env.NODE_ENV === 'prod' ? '../.env.prod' : '../.env.dev';
// env环境变量的路径
const envPath = path.resolve(__dirname, envfile);
// env对象
const envObj = parse(fs.readFileSync(envPath, 'utf8'));
const SERVER_ID = parseInt(envObj['VUE_APP_SERVER_ID']);

function parse(src) {
  // 解析KEY=VAL的文件
  const res = {};
  src.split('\n').forEach(line => {
    // matching "KEY' and 'VAL' in 'KEY=VAL'
    // eslint-disable-next-line no-useless-escape
    const keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
    // matched?
    if (keyValueArr != null) {
      const key = keyValueArr[1];
      let value = keyValueArr[2] || '';

      // expand newlines in quoted values
      const len = value ? value.length : 0;
      if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
        value = value.replace(/\\n/gm, '\n');
      }

      // remove any surrounding quotes and extra spaces
      value = value.replace(/(^['"]|['"]$)/g, '').trim();

      res[key] = value;
    }
  });
  return res;
}

/*
 *定义多个服务器账号 及 根据 SERVER_ID 导出当前环境服务器账号
 */
const SERVER_LIST = [
  {
    id: 0,
    name: 'A-生产环境',
    domain: 'www.prod.com',// 域名
    host: '46.106.38.24',// ip
    port: 22,// 端口
    username: 'root', // 登录服务器的账号
    password: 'Rock@sz18!',// 登录服务器的账号
    path: '/mdm/nginx/dist'// 发布至静态服务器的项目路径
  },
  {
    id: 1,
    name: 'B-测试环境',
    domain: 'test.xxx.com',
    host: 'XX.XX.XX.XX',
    port: 22,
    username: 'root',
    password: 'xxxxxxx',
    path: '/usr/local/www/xxx_program_test/'
  }
];

module.exports = SERVER_LIST[SERVER_ID];
Copy after login

三、使用scp2库,创建自动化部署脚本

在项目根目录下, 创建 deploy/index.js 文件

const scpClient = require('scp2');
const ora = require('ora');
const chalk = require('chalk');
const server = require('./products');
const spinner = ora('正在发布到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器...');
spinner.start();
scpClient.scp(
  'dist/',
  {
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password,
    path: server.path
  },
  function (err) {
    spinner.stop();
    if (err) {
      console.log(chalk.red('发布失败.\n'));
      throw err;
    } else {
      console.log(chalk.green('Success! 成功发布到' + (process.env.NODE_ENV === 'prod' ? '生产' : '测试') + '服务器! \n'));
    }
  }
);
Copy after login

四、添加 package.json 中的 scripts 命令, 自定义名称为 "deploy",

发布到测试环境命令为 npm run deploy:dev,生产环境为 npm run deploy:prod

  "scripts": {
    "serve": "vue-cli-service serve --mode dev",
    "build": "vue-cli-service build --mode prod",
    "deploy:dev": "npm run build && cross-env NODE_ENV=dev node ./deploy",
    "deploy:prod": "npm run build && cross-env NODE_ENV=prod node ./deploy",
  },
Copy after login

ps 这里用到了cross_env  得安装 npm i --save-dev cross-env cross-env能跨平台地设置及使用环境变量,这里用来设置是生产环境还是测试环境。

图解

Introduction to the method of automatically deploying projects to the server with Vue-CLI 3.x (code)

【相关推荐:JavaScript视频教程

The above is the detailed content of Introduction to the method of automatically deploying projects to the server with Vue-CLI 3.x (code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

What underlying technologies does Docker use? What underlying technologies does Docker use? Apr 15, 2025 am 07:09 AM

Docker uses container engines, mirror formats, storage drivers, network models, container orchestration tools, operating system virtualization, and container registry to support its containerization capabilities, providing lightweight, portable and automated application deployment and management.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

See all articles