One place for hosting & domains

      Environment

      How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 18.04


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      PHP is a popular server scripting language known for creating dynamic and interactive web pages. Getting up and running with your language of choice is the first step in learning to program.

      This tutorial will guide you through installing PHP 7.4 on Ubuntu and setting up a local programming environment via the command line. You will also install a dependency manager, Composer, and test your installation by running a script.

      Prerequisites

      To complete this tutorial, you will need a local or virtual machine with Ubuntu 18.04 installed and have administrative access and an internet connection to that machine. You can download this operating system via the Ubuntu releases page.

      Step 1 — Setting Up PHP 7.4

      You’ll be completing your installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well.

      The command line, also known as a shell or terminal, can help you modify and automate many of the tasks you do on a computer every day and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. The article An Introduction to the Linux Terminal can get you better oriented with the terminal.

      On Ubuntu, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left-hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically.

      Ubuntu terminal

      You will want to avoid relying on the default version of PHP because that default version could change depending on where you are running your code. You may also wish to install a different version to match an application you are using or to upgrade to a newer version, such as PHP 8.

      Run the following command to update apt-get itself, which ensures that you have access to the latest versions of anything you want to install:

      Next, install software-properties-common, which adds management for additional software sources:

      • sudo apt -y install software-properties-common

      The -y flag will automatically agree to the installation. Without that, you would receive a prompt in your terminal window for each installation.

      Next, install the repository ppa:ondrej/php, which will give you all your versions of PHP:

      • sudo add-apt-repository ppa:ondrej/php

      Finally, you update apt-get again so your package manager can see the newly listed packages:

      Now you’re ready to install PHP 7.4 using the following command:

      • sudo apt -y install php7.4

      Check the version installed:

      You will receive something similar to the following:

      Output

      PHP 7.4.0beta4 (cli) (built: Aug 28 2019 11:41:49) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0-dev, Copyright (c) Zend Technologies with Zend OPcache v7.4.0beta4, Copyright (c), by Zend Technologies

      Besides PHP itself, you will likely want to install some additional PHP modules. You can use this command to install additional modules, replacing PACKAGE_NAME with the package you wish to install:

      • sudo apt-get install php7.4-PACKAGE_NAME

      You can also install more than one package at a time. Here are a few suggestions of the most common modules you will most likely want to install:

      • sudo apt-get install -y php7.4-cli php7.4-json php7.4-common php7.4-mysql php7.4-zip php7.4-gd php7.4-mbstring php7.4-curl php7.4-xml php7.4-bcmath

      This command will install the following modules:

      • php7.4-cli - command interpreter, useful for testing PHP scripts from a shell or performing general shell scripting tasks
      • php7.4-json - for working with JSON data
      • php7.4-common - documentation, examples, and common modules for PHP
      • php7.4-mysql - for working with MySQL databases
      • php7.4-zip - for working with compressed files
      • php7.4-gd - for working with images
      • php7.4-mbstring - used to manage non-ASCII strings
      • php7.4-curl - lets you make HTTP requests in PHP
      • php7.4-xml - for working with XML data
      • php7.4-bcmath - used when working with precision floats

      PHP configurations related to Apache are stored in /etc/php/7.4/apache2/php.ini. You can list all loaded PHP modules with the following command:

      You have installed PHP and verified the version you have running. You also installed any required PHP modules and were able to list the modules that you have loaded.

      You could start using PHP right now, but you will likely want to use various libraries to build PHP applications quickly. Before you test your PHP environment, first set up a dependency manager for your projects.

      Step 2 — Setting Up Composer for Dependency Management (Optional)

      Libraries are a collection of code that can help you solve common problems without needing to write everything yourself. Since there are many libraries available, using a dependency manager will help you manage multiple libraries as you become more experienced in writing PHP.

      Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and will manage installing and updating these packages.

      Although similar, Composer is not a package manager in the same sense as yum or apt. It deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does, however, support a global project for convenience via the global command.

      This idea is not new, and Composer is strongly inspired by Node’s npm and Ruby’s bundler.

      Suppose:

      • You have a project that depends on several libraries.
      • Some of those libraries depend on other libraries.

      Composer:

      • Enables you to declare the libraries you depend on.
      • Finds out which versions of which packages can and need to be installed and installs them by downloading them into your project.
      • Enables you to update all your dependencies in one command.
      • Enables you to see the Basic Usage chapter for more details on declaring dependencies.

      There are, in short, two ways to install Composer: locally as part of your project or globally as a system-wide executable. Either way, you will start with the local install.

      Locally

      To quickly install Composer in the current directory, run this script in your terminal:

      • php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
      • php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
      • php composer-setup.php
      • php -r "unlink('composer-setup.php');"

      This installer script will check some php.ini settings, warn you if they are set incorrectly, and then download the latest composer.phar in the current directory. The four lines will, in order:

      • Download the installer to the current directory
      • Verify the installer SHA-384, which you can also cross-check here
      • Run the installer
      • Remove the installer

      The installer will check a few PHP settings and then download composer.phar to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP that can be run on the command line, amongst other things.

      In order to run Composer, you use php composer.phar. As an example, run this command to see the version of Composer you have installed:

      • php composer.phar --version

      To use Composer locally, you will want your composer.phar file to be in your project’s root directory. You can start in your project directory before installing Composer. You can also move the file after installation. You can also install Composer to a specific directory by using the --install-dir option and additionally (re)name it using the --filename option.

      Since Composer is something used across projects, it’s recommended that you continue to the next portion and set Composer to run globally.

      Globally

      You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your $PATH, you can access it globally. You can even make it executable on Ubuntu (and other Unix systems) and invoke it without directly using the PHP interpreter.

      After installing locally, run this command to move composer.phar to a directory that is in your path:

      • sudo mv composer.phar /usr/local/bin/composer

      If you’d like to install it only for your user and avoid requiring root permissions, you can use ~/.local/bin instead, which is available by default on some Linux distributions:

      • mv composer.phar ~/.local/bin/composer

      Now to run Composer, use composer instead of php composer.phar. To check for your Composer version, run:

      As a final step, you may optionally initialize your project with composer init. This will create the composer.json file that will manage your project dependencies. Initializing the project will also let you define project details such as Author and License, and use Composer’s autoload functionality. You can define dependencies now or add them later.

      Run this command to initialize a project:

      Running this command will start the setup wizard. Details that you enter in the wizard can be updated later, so feel free to leave the defaults and just press ENTER. If you aren’t ready to install any dependencies, you can choose no. Enter in your details at each prompt:

      Output

      This command will guide you through creating your composer.json config. Package name (sammy/php_install): sammy/project1 Description []: Author [Sammy <sammy@digitalocean.com>, n to skip]: Minimum Stability []: Package Type (e.g. library, project, metapackage, composer-plugin) []: project License []: Define your dependencies. Would you like to define your dependencies (require) interactively [yes]? no Would you like to define your dev dependencies (require-dev) interactively [yes]? no { "name": "sammy/project1", "type": "project", "authors": [ { "name": "Sammy", "email": "sammy@digitalocean.com" } ], "require": {} } Do you confirm generation [yes]? yes

      Before you confirm the generation, you will see a sample of the composer.json file that the wizard will create. If it all looks good, you can confirm the default of yes. If you need to start over, choose no.

      The first time you define any dependency, Composer will create a vendor folder. All dependencies install into this vendor folder. Composer also creates a composer.lock file. This file specifies the exact version of each dependency and subdependency used in your project. This assures that any machine on which your program is run, will be using the exact same version of each packages.

      Note: The vendor folder should never be committed to your version control system (VCS). The vendor folder only contains packages you have installed from other vendors. Those individual vendors will maintain their own code in their own version control systems. You should only be tracking the code you write. Instead of committing the vendor folder, you only need to commit your composer.json and composer.lock files. You can learn more about ignoring specific files in How To Use Git: A Reference Guide.

      Now that you have PHP installed and a way to manage your project dependencies using Composer, you’re ready to test your environment.

      Step 3 — Testing the PHP Environment

      To test that your system is configured correctly for PHP, you can create and run a basic PHP script. Call this script hello.php:

      This will open a blank file. Put the following text, which is valid PHP code, inside the file:

      hello.php

      <?php
      echo 'Hello World!';
      ?>
      

      Once you’ve added the text, save and close the file. You can do this by holding down the CTRL key and pressing the x key. Then choose y and press ENTER.

      Now you can test to make sure that PHP processes your script correctly. Type php to tell PHP to process the file, followed by the name of the file:

      If the PHP is processed properly, you will see only the characters within the quotes:

      Output

      Hello World!

      PHP has successfully processed the script, meaning that your PHP environment is successfully installed and you’re ready to continue your programming journey.

      Conclusion

      At this point, you have a PHP 7.4 programming environment set up on your local Ubuntu machine and can begin a coding project.

      Before you start coding, you may want to set up an Integrated Development Environment (IDE). While there are many IDEs to choose from, VS Code is a popular choice as it offers many powerful features such as a graphical interface, syntax highlighting, and debugging.

      With your local machine ready for software development, you can continue to learn more about coding in PHP by following How To Work With Strings in PHP.



      Source link

      How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      PHP is a popular server scripting language known for creating dynamic and interactive web pages. Getting up and running with your language of choice is the first step in learning to program.

      This tutorial will guide you through installing PHP 7.4 on Ubuntu and setting up a local programming environment via the command line. You will also install a dependency manager, Composer, and test your installation by running a script.

      Prerequisites

      To complete this tutorial, you will need a local or virtual machine with Ubuntu 20.04 installed and have administrative access and an internet connection to that machine. You can download this operating system via the Ubuntu releases page.

      Step 1 — Setting Up PHP 7.4

      You’ll be completing your installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well.

      The command line, also known as a shell or terminal, can help you modify and automate many of the tasks you do on a computer every day and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. The article An Introduction to the Linux Terminal can get you better oriented with the terminal.

      On Ubuntu, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left-hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically.

      Ubuntu terminal

      Note: Ubuntu 20.04 ships with PHP 7.4 in its upstream repositories. This means that if you attempt to install PHP without a specified version, it will use 7.4.

      You will want to avoid relying on the default version of PHP because that default version could change depending on where you are running your code. You may also wish to install a different version to match an application you are using or to upgrade to a newer version, such as PHP 8.

      Run the following command to update apt-get itself, which ensures that you have access to the latest versions of anything you want to install:

      Next, install software-properties-common, which adds management for additional software sources:

      • sudo apt -y install software-properties-common

      The -y flag will automatically agree to the installation. Without that, you would receive a prompt in your terminal window for each installation.

      Next, install the repository ppa:ondrej/php, which will give you all your versions of PHP:

      • sudo add-apt-repository ppa:ondrej/php

      Finally, you update apt-get again so your package manager can see the newly listed packages:

      Now you’re ready to install PHP 7.4 using the following command:

      • sudo apt -y install php7.4

      Check the version installed:

      You will receive something similar to the following:

      Output

      PHP 7.4.0beta4 (cli) (built: Aug 28 2019 11:41:49) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0-dev, Copyright (c) Zend Technologies with Zend OPcache v7.4.0beta4, Copyright (c), by Zend Technologies

      Besides PHP itself, you will likely want to install some additional PHP modules. You can use this command to install additional modules, replacing PACKAGE_NAME with the package you wish to install:

      • sudo apt-get install php7.4-PACKAGE_NAME

      You can also install more than one package at a time. Here are a few suggestions of the most common modules you will most likely want to install:

      • sudo apt-get install -y php7.4-cli php7.4-json php7.4-common php7.4-mysql php7.4-zip php7.4-gd php7.4-mbstring php7.4-curl php7.4-xml php7.4-bcmath

      This command will install the following modules:

      • php7.4-cli - command interpreter, useful for testing PHP scripts from a shell or performing general shell scripting tasks
      • php7.4-json - for working with JSON data
      • php7.4-common - documentation, examples, and common modules for PHP
      • php7.4-mysql - for working with MySQL databases
      • php7.4-zip - for working with compressed files
      • php7.4-gd - for working with images
      • php7.4-mbstring - used to manage non-ASCII strings
      • php7.4-curl - lets you make HTTP requests in PHP
      • php7.4-xml - for working with XML data
      • php7.4-bcmath - used when working with precision floats

      PHP configurations related to Apache are stored in /etc/php/7.4/apache2/php.ini. You can list all loaded PHP modules with the following command:

      You have installed PHP and verified the version you have running. You also installed any required PHP modules and were able to list the modules that you have loaded.

      You could start using PHP right now, but you will likely want to use various libraries to build PHP applications quickly. Before you test your PHP environment, first set up a dependency manager for your projects.

      Step 2 — Setting Up Composer for Dependency Management (Optional)

      Libraries are a collection of code that can help you solve common problems without needing to write everything yourself. Since there are many libraries available, using a dependency manager will help you manage multiple libraries as you become more experienced in writing PHP.

      Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and will manage installing and updating these packages.

      Although similar, Composer is not a package manager in the same sense as yum or apt. It deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does, however, support a global project for convenience via the global command.

      This idea is not new, and Composer is strongly inspired by Node’s npm and Ruby’s bundler.

      Suppose:

      • You have a project that depends on several libraries.
      • Some of those libraries depend on other libraries.

      Composer:

      • Enables you to declare the libraries you depend on.
      • Finds out which versions of which packages can and need to be installed and installs them by downloading them into your project.
      • Enables you to update all your dependencies in one command.
      • Enables you to see the Basic Usage chapter for more details on declaring dependencies.

      There are, in short, two ways to install Composer: locally as part of your project or globally as a system-wide executable. Either way, you will start with the local install.

      Locally

      To quickly install Composer in the current directory, run this script in your terminal:

      • php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
      • php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
      • php composer-setup.php
      • php -r "unlink('composer-setup.php');"

      This installer script will check some php.ini settings, warn you if they are set incorrectly, and then download the latest composer.phar in the current directory. The four lines will, in order:

      • Download the installer to the current directory
      • Verify the installer SHA-384, which you can also cross-check here
      • Run the installer
      • Remove the installer

      The installer will check a few PHP settings and then download composer.phar to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP that can be run on the command line, amongst other things.

      In order to run Composer, you use php composer.phar. As an example, run this command to see the version of Composer you have installed:

      • php composer.phar --version

      To use Composer locally, you will want your composer.phar file to be in your project’s root directory. You can start in your project directory before installing Composer. You can also move the file after installation. You can also install Composer to a specific directory by using the --install-dir option and additionally (re)name it using the --filename option.

      Since Composer is something used across projects, it’s recommended that you continue to the next portion and set Composer to run globally.

      Globally

      You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your $PATH, you can access it globally. You can even make it executable on Ubuntu (and other Unix systems) and invoke it without directly using the PHP interpreter.

      After installing locally, run this command to move composer.phar to a directory that is in your path:

      • sudo mv composer.phar /usr/local/bin/composer

      If you’d like to install it only for your user and avoid requiring root permissions, you can use ~/.local/bin instead, which is available by default on some Linux distributions:

      • mv composer.phar ~/.local/bin/composer

      Now to run Composer, use composer instead of php composer.phar. To check for your Composer version, run:

      As a final step, you may optionally initialize your project with composer init. This will create the composer.json file that will manage your project dependencies. Initializing the project will also let you define project details such as Author and License, and use Composer’s autoload functionality. You can define dependencies now or add them later.

      Run this command to initialize a project:

      Running this command will start the setup wizard. Details that you enter in the wizard can be updated later, so feel free to leave the defaults and just press ENTER. If you aren’t ready to install any dependencies, you can choose no. Enter in your details at each prompt:

      Output

      This command will guide you through creating your composer.json config. Package name (sammy/php_install): sammy/project1 Description []: Author [Sammy <sammy@digitalocean.com>, n to skip]: Minimum Stability []: Package Type (e.g. library, project, metapackage, composer-plugin) []: project License []: Define your dependencies. Would you like to define your dependencies (require) interactively [yes]? no Would you like to define your dev dependencies (require-dev) interactively [yes]? no { "name": "sammy/project1", "type": "project", "authors": [ { "name": "Sammy", "email": "sammy@digitalocean.com" } ], "require": {} } Do you confirm generation [yes]? yes

      Before you confirm the generation, you will see a sample of the composer.json file that the wizard will create. If it all looks good, you can confirm the default of yes. If you need to start over, choose no.

      The first time you define any dependency, Composer will create a vendor folder. All dependencies install into this vendor folder. Composer also creates a composer.lock file. This file specifies the exact version of each dependency and subdependency used in your project. This assures that any machine on which your program is run, will be using the exact same version of each packages.

      Note: The vendor folder should never be committed to your version control system (VCS). The vendor folder only contains packages you have installed from other vendors. Those individual vendors will maintain their own code in their own version control systems. You should only be tracking the code you write. Instead of committing the vendor folder, you only need to commit your composer.json and composer.lock files. You can learn more about ignoring specific files in How To Use Git: A Reference Guide.

      Now that you have PHP installed and a way to manage your project dependencies using Composer, you’re ready to test your environment.

      Step 3 — Testing the PHP Environment

      To test that your system is configured correctly for PHP, you can create and run a basic PHP script. Call this script hello.php:

      This will open a blank file. Put the following text, which is valid PHP code, inside the file:

      hello.php

      <?php
      echo 'Hello World!';
      ?>
      

      Once you’ve added the text, save and close the file. You can do this by holding down the CTRL key and pressing the x key. Then choose y and press ENTER.

      Now you can test to make sure that PHP processes your script correctly. Type php to tell PHP to process the file, followed by the name of the file:

      If the PHP is processed properly, you will see only the characters within the quotes:

      Output

      Hello World!

      PHP has successfully processed the script, meaning that your PHP environment is successfully installed and you’re ready to continue your programming journey.

      Conclusion

      At this point, you have a PHP 7.4 programming environment set up on your local Ubuntu machine and can begin a coding project.

      Before you start coding, you may want to set up an Integrated Development Environment (IDE). While there are many IDEs to choose from, VS Code is a popular choice as it offers many powerful features such as a graphical interface, syntax highlighting, and debugging.

      With your local machine ready for software development, you can continue to learn more about coding in PHP by following How To Work With Strings in PHP.



      Source link

      How To Use Vue.js Environment Modes with a Node.js Mock Data Layer


      The author selected Open Sourcing Mental Illness to receive a donation as part of the Write for DOnations program.

      Introduction

      When it comes to software development, there are two ends of the stack. A stack is a collection of technologies used for your software to function. Vue.js, the progressive user interface framework, is part of the frontend, the part of the stack that a user directly interacts with. This frontend is also referred to as the client and encompasses everything that is rendered in the user’s browser. Technologies such as HTML, JavaScript, and CSS are all rendered in the client. In contrast, the backend commonly interacts with data or servers through technologies like Java, Kotlin, or .NET.

      The application is the data itself, and the interface (frontend) is a way to display data meaningfully to the user for them to interact with. In the begining phase of software development, you don’t need a backend to get started. In some cases, the backend hasn’t even been created yet. In a case such as this, you can create your own local data to build your interface. Using Node environments and variables, you can toggle different datasets per environment or toggle between local data and “live” data via a network call. Having a mock data layer is useful if you do not have data yet, because it provides data to test your frontend before the backend is ready.

      By the end of this tutorial, you will have created several Node environments and toggled these datasets with Node environment variables. To illustrate these concepts, you will create a number of Vue components to visualize this data across environments.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Creating Environments with Modes

      Modes are an important concept when it comes to Vue CLI projects. A mode is an environment type, or a set of variables that gets loaded during a build. These variables are stored in .env files in the root directory of your project. As part of the default vue-cli-service plugin, you immediately have access to three modes. These are:

      • development: used when vue-cli-service serve is executed.
      • test: used when vue-cli-service test:unit is executed.
      • production: used when vue-cli-service build and vue-cli-service test:e2e are executed.

      Perhaps the most used mode is development mode. This is the mode that Vue.js developers use when working on their application on their local machine. This mode starts a local Node server with hot-module reloading (instant browser refreshing) enabled. The test mode, on the other hand, is a mode to run your unit tests in. Unit tests are JavaScript functions that test application methods, events, and in some cases, user interaction. The last default mode is production. This compressess all of your code and optimizes it for performance so it can be hosted on a production server.

      The project that is generated for you from Vue CLI has these commands pre-mapped to npm run serve, npm run test:unit, and npm run build.

      Each environment is associated with its own .env file, where you can put custom Node environment key/value pairs that your application can reference. You will not have these files after generating a project from the CLI, but you can add these using one command in your terminal.

      You will now generate a development environment file, which you will use later in the tutorial. Open your terminal and enter the following in the root directory of your project:

      Open the newly created file in your text editor of choice. In this file, you’ll want to explicitly define the environment type. This is a key/value pair that could be anything you want. However, it’s considered best practice to define the environment type that corresponds with the name of the .env file.

      You will be using this NODE_ENV later in the tutorial by loading different data sets depending on the environment or mode selected on build. Add the following line:

      .env.development

      NODE_ENV="development"
      

      Save and exit the file.

      The key/value pairs in this file will only affect your program when the application is in development mode. It’s important to note that Git will automatically commit these files unless you add the file in your .gitignore file or append the .local extension to the file name: .env.development.local.

      You are not limited to the standard environments that Vue.js provides. You may have several other environments that are specific to your workflow. Next, you’ll create a custom environment for a staging server.

      Start by creating the .env file for the staging environment. Open your terminal of choice and in the root directory run the following:

      In this file, create a key/value pair that’ll define the NODE_ENV of this project. You may open this file in your text editor of choice, or you can modify it using the terminal. Nano is an editor that is used in the terminal window. You may have other editors such as Vim.

      You will be using this NODE_ENV later in the tutorial by loading different data sets depending on the environment or mode selected on build.

      Add the following to the file:

      .env.staging

      NODE_ENV="staging"
      

      Save and exit the file. In nano, you can save the file with CTRL+X then CTRL+Y.

      In order to use this environment, you can register a new script in your package.json file. Open this file now.

      In the "scripts" section, add the following highlighted line:

      package.json

      {
        ...
        "scripts": {
          ...
          "staging": "vue-cli-service serve --mode staging",
        },
        ...
      }
      

      Save this file, then exit the editor.

      You’ve just created a new script that can be executed with npm run staging. The flag --mode lets Vue CLI know to use the .env.staging (or .env.staging.local) file when starting the local server.

      In this step, you created custom NODE_ENV variables for two Vue.js modes: development and staging. These modes will come in handy in the following steps when you create custom datasets for each of these modes. By running the project in one mode or the other, you can load different data sets by reading these files.

      Step 2 — Creating a Mock Data Layer

      As stated in the Introduction, you can start developing your user interface without a backend by using a mock data layer. A mock data layer is static data that is stored locally for your application to reference. When working with Vue, these data files are JavaScript objects and arrays. Where these are stored is your personal preference. For the sake of this tutorial, mock data files will be stored in a directory named data.

      In this tutorial, you’re building a “main/detail” airport browser application. In the “main” view, the user will see a number of airport codes and locations.

      In your terminal, in the root project directory, create a new directory using the mkdir command:

      Now create a .js file named airports.staging.mock.js using the touch command. Naming these files is personal preference, but it’s generally a good idea to differentiate this mock data from essential files in your app. For the sake of this tutorial, mock files will follow this naming convention: name.environment.mock.js.

      Create the file with the following command:

      • touch data/airports.staging.mock.js

      In your editor of choice, open this newly created JavaScript file and add the following array of objects:

      data/airports.staging.mock.js

      const airports = [
          {
              name: 'Cincinnati/Northern Kentucky International Airport',
              abbreviation: 'CVG',
              city: 'Hebron',
              state: 'KY'
          },
          {
              name: 'Seattle-Tacoma International Airport',
              abbreviation: 'SEA',
              city: 'Seattle',
              state: 'WA'
          },
          {
              name: 'Minneapolis-Saint Paul International Airport',
              abbreviation: 'MSP',
              city: 'Bloomington',
              state: 'MN'
          }
      ]
      
      export default airports
      

      In this code block, you are creating objects that represent airports in the United States and providing their name, abbreviation, and the city and state in which they are located. You then export the array to make it available to other parts of your program. This will act as your “staging” data.

      Next, create a dataset for another environment like “development"—the default environment when running npm run serve. To follow the naming convention, create a new file in your terminal with the touch command and name it airports.development.mock.js:

      • touch data/airports.development.mock.js

      In your editor of choice, open this newly created JavaScript file and add the following array of objects:

      data/airports.development.mock.js

      const airports = [
          {
              name: 'Louis Armstrong New Orleans International Airport',
              abbreviation: 'MSY',
              city: 'New Orleans',
              state: 'LA'
          },
          {
              name: 'Denver International Airport',
              abbreviation: 'DEN',
              city: 'Denver',
              state: 'CO'
          },
          {
              name: 'Philadelphia International Airport',
              abbreviation: 'PHL',
              city: 'Philadelphia',
              state: 'PA'
          }
      ]
      
      export default airports
      

      This will act as your "development” data when you run npm run serve.

      Now that you’ve created the mock data for your environments, in the next step, you are going to iterate or loop through that data with the v-for directive and start building out the user interface. This will give you a visual representation of the change when using the different modes.

      Step 3 — Iterating Through Mock Data in App.vue

      Now that you have your mock data, you can test out how useful environments are by iterating through this data in the App.vue component in the src directory.

      First, open up App.vue in your editor of choice.

      Once it is open, delete all of the HTML inside the template tags and remove the import statement in the script section. Also, delete the HelloWorld component in the export object. Some general styles have also been provided to make the data easier to read.

      Add the following highlighted lines to your App.vue file:

      src/App.vue

      <template>
      
      </template>
      
      <script>
      export default {
        name: 'App',
      }
      </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;
      }
      
      .wrapper {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 1rem;
        max-width: 960px;
        margin: 0 auto;
      }
      
      .airport {
        border: 3px solid;
        border-radius: .5rem;
        padding: 1rem;
      }
      
      .airport p:first-child {
        font-weight: bold;
        font-size: 2.5rem;
        margin: 1rem 0;
      <^>}
      
      .airport p:last-child {
        font-style: italic;
        font-size: .8rem;
      }
      </style>
      

      In this case, CSS Grid is being used to create these cards of airport codes into a grid of three. Notice how this grid is set up in the .wrapper class. The .airport is the card or section that contains each airport code, name, and location.

      Next, import the development mock data that was created earlier. Since this is vanilla JavaScript, you can import it via an import statement. You will also need to register this data with the data property so the Vue template has access to this data.

      Add the following highlighted lines:

      src/App.vue

      ...
      <script>
      import airports from '../data/airports.development.mock'
      
      export default {
        name: 'App',
        data() {
          return {
            airports
          }
        }
      }
      </script>
      ...
      

      Now that the mock data has been imported, you can start using it to build your interface. In the case of this application, iterate through this data with the v-for directive and display it in your template:

      src/App.vue

      <template>
        <div class="wrapper">
          <div v-for="airport in airports" :key="airport.abbreviation" class="airport">
            <p>{{ airport.abbreviation }}</p>
            <p>{{ airport.name }}</p>
            <p>{{ airport.city }}, {{ airport.state }}</p>
          </div>
        </div>
      </template>
      ...
      

      v-for in this case is used to render the list of airports.

      Save and close the file.

      In your terminal, start the development server by running the command:

      Vue CLI will provide you a local address, generally localhost:8080. Visit that addresss in your browser of choice. You will find the data from airports.development.mock.js rendered in your browser:

      Styled cards containing airport data from the development dataset.

      At this point, you created a static mock data layer and loaded it when you executed npm run serve. However, you will notice that if you stop the server (CTRL+C) and start the staging environment, you will have the same result in your browser. In this next step, you are going to tell your app to load a set of data for each environment. To achieve this, you can use a Vue computed property.

      Step 4 — Loading Environment-Specific Data with Computed Properties

      In Vue, computed properties are component functions that must return a value. These functions cannot accept arguments, and are cached by Vue. Computed properties are very useful when you need to perform logic and assign that return value to a property. In this respect, computed properties act similar to data properties as far as the template is concerned.

      In this step, you will use computed properties to use different datasets for the staging and the development environment.

      Start by opening src/App.vue and importing both sets of data:

      src/App.vue

      ...
      <script>
      import DevData from '../data/airports.development.mock'
      import StagingData from '../data/airports.staging.mock'
      
      export default {
        name: 'App',
        ...
      }
      </script>
      ...
      

      If you still have one of the environments running, your data will disappear. That is because you removed the data property that connected your JavaScript mock data to the template.

      Next, create a computed property named airports. The function name is important here because Vue is taking the return value of the function and assigning it to airports for the template to consume. In this computed property, you’ll need to write a bit of logic; an if/else statement that evaluates the Node environment name. To get the value of the Node environment in Vue, you can access it with process.env.NODE_ENV. When you created your Node environments, Vue automatically assigned NODE_ENV to development and staging respectively.

      src/App.vue

      ...
      <script>
      import DevData from '../data/airports.development.mock'
      import StagingData from '../data/airports.staging.mock'
      
      export default {
        name: 'App',
        computed: {
            airports() {
              if (process.env.NODE_ENV === 'development') return DevData
              else return StagingData
            }
        }
      }
      </script>
      ...
      

      Now you are loading each set of data per its respective environment.

      In your terminal, start the local development environment with npm run serve.

      The data will be identical to what it was before.

      Now, start the staging environment by first stopping the server and then executing npm run staging in your terminal window.

      When you visit localhost:8080 in your browser, you will find a different set of data.

      Styled cards containing airport data from the staging dataset.

      Conclusion

      In this tutorial, you worked with different Vue.js environment modes and added environment scripts to your package.json file. You also created mock data for a number of environments and iterated through the data using the v-for directive.

      By using this approach to make a temporary backend, you can focus on the development of your interface and the frontend of your application. You are also not limited to any number of environments or the default environments provided by Vue. It isn’t uncommon to have .env files for four or more environments: development, staging, user acceptance testing (UAT), and production.

      For more information on Vue.js and Vue CLI 3, it’s recommended to read through their documentation. For more tutorials on Vue, check out the Vue Topic Page.



      Source link