preface

Coding should be a lifelong career, not just 30 youth 🍚 this article has included making https://github.com/ponkans/F2E, welcome to Star, continuously updated 💧

P6 front-end necessary scaffolding /CI construction ability, look down along the strange idea, and then get the source code at the end of the article, follow the source code operation again, is a complete front-end scaffolding construction, release, deployment engineering project.

The CLI in this article has been published to the NPM repository as follows:


I hope you learned something from each article. This is an automated build deployment for a front-end project. I hope you learned something after reading this article:

  • CLI Create a remote repository
  • CLI package
  • Nginx deployment
  • Webhook triggers Jenkins to package deployment services
  • Jenkins package deployment
  • CI build

Architecture diagram

The project initialization, template pull, and project run sections on the left are already implemented in the large Front-end Advanced Node.js series P6 required scaffolding /CI build capability (part 1).

Today, the implementation of the right part, which is the CI part (we usually use the front-end project release system, roughly such a thing).

Complete architecture

preparation

Making account

Project if it is stored in the local easily because some unexpected circumstances (such as coffee, and daughter-in-law fight computer fell, etc.) cause code is missing, and inconvenient people development and maintenance of cooperation, so we are all need to remote warehouse storage project, this article USES the making warehouse, if you want to practice, Get your GitHub account ready.

server

To enable users to access our web pages on the Internet through a client such as a web browser, we need a server to deploy the project so that users can access our web pages through a public IP address.

Aliyun Server is used in this paper. You can also prepare one if you have conditions. Of course, don’t panic if you don’t have conditions.

Server deployment

  • Install Nginx

  • Install the node

  • Install yum

    PS: Yum is a Shell front-end package manager. Based on RPM package management, RPM packages can be automatically downloaded and installed from the specified server. The dependency relationship can be automatically handled and all dependent software packages can be installed at one time without tedious downloading and installation.

    For example, Jenkins uses Yum to install easily and quickly.

CLI Create a remote repository

Command line to create the warehouse

Sometimes, in order to synchronize the local project repository to Github, we have to open the browser to create an empty repository under our Github account, which interrupts our workflow. Wouldn’t it be perfect if we could create the Github repository and associate it with the local project through the command line? The command line can also be integrated into our CLI tools. If you can’t think of anything that can’t be done, here’s how to create a repository using the command line.

Start by creating a token creation address on your Github. This token will be used for verification when creating projects on the command line

(I checked all the scopes in the last two scopes, but I didn’t have time to study them carefully. Sorry for that.)

Be sure to save the generated Personal Access token. It will only be displayed once. If you don’t write it down, you won’t find it later

Create the Github repository from the command line
curl -u "$username:$token" https://api.github.com/user/repos -d '{"name":"$repo_name"}'

Copy the code

Here you need to replace the username and token above with the actual username and the Personal Access token you just remembered, and replace the repo_name with any desired repository name.

Integrate the Github repository function from the command line into the CLI tool

In our previous article, we introduced that the CLI has a function to initialize Github repositories. Next, we will add the function to the CLI to initialize Github repositories.

  • Git initialization
  • Create the Github repository
  • Associate the Github repository
  • Update the repository configuration for package.json
  • Submit the code to the Github repository
  • Install dependencies

The code is in little-bird-cli/ SRC /init.js

try {

  await loadCmd(`git init`.Git initialization);

  if (username === ' ' || token === ' ') {

    console.log(symbol.warning, chalk.yellow('Remote warehouse cannot be created due to missing entry'));

  } else {

    const projectName = process.cwd().split('/').slice(- 1) [0];



    await loadCmd(`curl -u "${username}:${token}" https://api.github.com/user/repos -d '{"name": "${projectName}"} '`.'Github repository creation ')

    await loadCmd(`git remote add origin https://github.com/${username}/${projectName}.git`.'Associate remote repository')

    let loading = ora();

    loading.start('package.json update repository: in execution... `);

    await updateJsonFile('package.json', {

      "repository": {

        "type""git".

        "url"`https://github.com/${username}/${projectName}.git`

      }

    }).then((a)= > {

      loading.succeed('package.json update repository: command executed');

    });



    await loadCmd(`git add .`.'Run git add')

    await loadCmd(`git commit -a -m 'init'`.'Git commit')

    await loadCmd(`git push --set-upstream origin master`.'Execute git push')

  }

  await loadCmd(`npm install`.'Install dependencies')

catch (err) {

  console.log(symbol.error, chalk.red('Initialization failed'));

  console.log(symbol.error, chalk.red(err));

  process.exit(1);

}

Copy the code

LBC init -u username -t token LBC init -u username -t token So congratulations, go to Github remote repository and check your project code

At this point, we can directly across the mountains and rivers, began Coding, both ears do not hear things outside the window, only to write code, it is really cool

Manual packaging & deployment

packaging

Packaging can be understood as the pre-processing work for online release, which will preprocess and transform the syntax that cannot be recognized by the browser, and compress All JS files and CSS files into an All in One.js and.css file respectively.

In this way, the browser can obtain the required front-end resources through a small number of HTTP requests, saving traffic and speeding up page loading. Currently, the popular packaging tools include Gulp, Grunt, Webpack and so on.

Our CLI tools already include WebPack, so we’ll use WebPack for packaging.

lbc build

Added package command LBC build to little-bird-cli/ SRC /main.js command management file

webpack.build.js

Add the webPack configuration file webpack.build.js. The main difference between this and our native project startup webPack configuration file is that it adds the package output and reduces some unnecessary methods such as listening.

output: {

  filename:'[name].[hash].js'.

  path: process.cwd() + '/dist'.

  publicPath'/'.

}

Copy the code
Execute the script

Added build execution script file little-bird-cli/ SRC /build.js

let build = (a)= > {

    webpack(config, (error) => {

        if(error ! = =null) {

            console.log(symbol.error, chalk.red(error));

        } else {

            console.log(symbol.success, chalk.green('Packed and done'));

        }

        process.exit(1);

    });

}

Copy the code

Execute LBC build in the project directory and look in the dist directory to see the HTML/JS files generated by the package

The deployment of

Before starting automatic deployment packaging, let’s experience manual deployment packaging to verify whether our CLI packaging command can be used normally on the server side.

The following operations are in the server environment ~😯

The login

Clone the project code to your server (after clone, don’t forget to install NPM install).

Install scaffold NPM package

Install CLI package NPM i-g little-bird-cli@latest globally

LBC build packaging

Run the LBC build package command in the project directory to see if there are HTML/JS files generated in the dist directory of your clone project. If so, CLI package is working on the server.

Nginx

To change the Nginx configuration, open the configuration file vim /etc/nginx/nginx.conf with root as the dist directory of your project

On Nginx, restart the Nginx service on Nginx -s reload. Then you can access your page on IP :80

Although by manual operation can also provide our project web page to the user to use, but every time a code update, need to push local code to the remote warehouse, and then login server pull code package code, repetitive tasks can save a province, invented tools are lazy 😆, lazy people below key is in the house, Once and for all

Many companies have their own front-end publishing systems that are not automated and need to be manually triggered for packaging and deployment

Automatic packaging & deployment infrastructure

Next, we use Jenkins+Github+Webhook automatic package deployment project to realize the automatic execution of script for package deployment when the Master branch submits.

You might say, what is Jenkins

Jenkins is open source CI software for automating a variety of tasks, including building, testing, and deploying software. To learn more, you can go to the official website.

What is Webhook

Often called React Hooks (not React Hooks, HHHH ~~), you can customize webhooks to check Github for various events, most commonly push events.

If you set up a Webhook that listens for push events, the Webhook will be triggered every time there is a submission for your project, and Github will send an HTTP POST to your configured address.

Let’s have a brief understanding of the concept (Google for details), and then we’ll start

The deployment server

Our first step is to deploy the server, first login your server (I seem nonsense, ha ha 😝).

Next, install Jenkins for your server. Since Jenkins requires a JDK environment to run, we also need to install the Java runtime environment on our own server.

Install the Java runtime environment

Check whether the JDK is installed on your server

java -version

Copy the code

If the above information is displayed, the JDK is not followed. You can install it through yum as follows

Run the yum -y list Java * command to check the version of Java that can be installed

# yum install java-1.8.0-openJDK-devel.x86_64 # yum install java-1.8.0-openJDK-devel.x86_64

Enter Java -version to check whether the installation is successful

Install Jenkins

Jenkins does not exist in yum Repos by default. You need to add Jenkins storage to yum Repos first

sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo

sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key

Copy the code

Install Jenkins by yum install Jenkins

Modifying Jenkins Configuration

By default, Jenkins is started by Jenkins user, but this user is not authorized by the system at present, so we change the start user to root. In addition, Jenkins default port 8080, if you have no other service to occupy port 8080, you can not change it.

vim /etc/sysconfig/jenkins

Copy the code

Modify the configuration

JENKINS_USER = 'root'

JENKINS_PORT = '8001'

Copy the code

Run service Jenkins start to start the Jenkins service

If the above information appears, Jenkins is successfully started. Enter * IP :8001 in the browser to access the Jenkins login page.

However ~ however ~ has been in turn circle, visit not, who am I where did I happen ❓

Confused for 1 second, start troubleshooting

First, check whether Jenkins is successfully started. Run systemctl status Jenkins to check Jenkins status

Jenkins is working fine, why can’t you access it? Oh!!

Run the systemctl status firewalld command to check the firewall status

Firewall not started, ok, no problem, let’s start it systemctl start firewalld

The firewall has been started, let’s check whether the firewall has opened the Jenkins port we set, run firewall-cmd –list-ports to find the Jenkins port, there is no problem, let’s open it

firewall-cmd --permanent --zone=public --add-port=80/tcp  // Enable the configured Jenkins port

systemctl reload firewalld // Restart the firewall to take effect

Copy the code

When I went to visit, full of hope and promise, my heart ached again

Then check aliyun firewall, Aliyun Server built-in firewall, default development only port 80, we use other ports need to go to aliyun firewall to open the port

Try again, tears eyes ~~ finally can visit

Configuration Jenkins

Jenkins provided us with the web configuration interface

When we got to the login page, Jenkins prompted us to enter the super administrator password to unlock it. According to the prompt, we can in the/var/lib/Jenkins/secrets/initialAdminPassword find password file.

tail /var/lib/jenkins/secrets/initialAdminPassword

Copy the code

Once you have found the password, copy it and paste it into the Jenkins unlock page. Click Continue to initialize the configuration. After a short wait, the plug-in installation page is displayed.

Here we click Install Suggested Plugins to Install the default plugin, but you can also click another button to Install the specified plugin. After clicking, the page enters the plug-in download and installation page.

After the installation is complete, the administrator account registration page is displayed.

After entering the information, click Save and Finish to enter the Jenkins welcome page (this picture is saved), and then click Start Using Jenkins to enter the Jenkins home page.

Now that the basic Jenkins configuration is complete, don’t panic, don’t panic, there is still work to do, and we will do some other configurations for Jenkins globally.

In the Github plugin configuration, click the “Advanced” button to enable Hook URL, and copy the Hook URL and save the Settings so that it can accept Github requests.

Configure the Github repository

Because Github often has code processing actions, it is necessary to configure Github project repository to send signals to Jenkins while processing these actions, so as to trigger Jenkins automatic build.

In the “Webhooks” TAB, click “Add webhook” and insert the Hook URL generated by Jenkins into the Payload URL. In addition, select Independent events and Events and select Intermediate events. Github triggers a Hook when it receives a Push action from a client

image-20200326180636869

After the configuration is complete, the following information is displayed

Automatic package deployment actual combat

The preliminary preparation is almost ready, the actual combat starts, first send the automatic packaging CI architecture diagram

This is actually a detailed version of the CI section on the ** right of the architecture diagram at the beginning of this article 😝~

create

To create the Jenkins project, select Freestyle Project

configuration

To Configure the project, click Configure to enter the configuration page for relevant configuration

Configuration making project URL: https://github.com/xxxxx/test

Configure Git repository address: https://github.com/xxxxx/test.git

Configure the build trigger event

Configuring the Build script

After save, serve in the r had our warehouse code, can go to/var/lib/Jenkins directory/workspace is precisely, or workspace to view web pages, web page view the need to build at least once.


Execute a build

After the build is complete, you can go to the workspace to see if there are any package files in dist

Modify the nginx configuration file, we have configured the nginx when manual packaging, pointing to the dist directory of our manual Clone project.

Then we change the root point to address to Jenkins created project dist directory/var/lib/Jenkins/workspace/hello/dist, restart the nginx, visit our Jenkins service created project

Git push = git push = Git push = Git push = Wow I ~

conclusion

This article has included making https://github.com/ponkans/F2E (I finishing a big front end knowledge skill tree in making), welcome to Star, continuously updated 💧

✨ strange I lazy words are not much, this period of code and figure a little more, small partners can directly obtain the source code, control the source code, their ideas again, to achieve again.

I believe that most of you who are reading this article will use scaffolding to do projects, package and publish them every day. Weirdo felt it was necessary and meaningful to understand and implement the whole front-end engineering process

Recently original portal, Biubiubiu ~~~

  • Large Front-end Advanced Node.js series P6 Essential Scaffolding /CI building ability (PART 1)
  • Collection of dACHang front-end component library tools (PC, mobile, JS, CSS, etc.)
  • Collection of essential front-end tools (package capture, debugging, Mock data, etc.)
  • Large front-end Advanced Node.js series Double eleven seconds kill system (advanced must see)

Like the small partner trouble to add a concern, a praise oh, Thanksgiving 💕😊

Contact me/public number

This article scaffolding /CI construction source code, public number reply [scaffolding] can be obtained, if interested in scaffolding later construction, please wechat private chat strange ~


Wechat search “water monster” or scan the qr code below reply “add group”, I will pull you into the technical communication group. Honestly, in this group, even if you don’t talk, just reading the chat is a kind of growth. (Ali technical experts, aobing authors, Java3y, mogujie senior front end, Ant Financial security experts, all the big names).

The water monster will also be regular original, regular with small partners to exchange experience or help read the resume. Add attention, don’t get lost, have a chance to run together 🏃 ↓↓↓