One place for hosting & domains

      CLI

      Getting Started With Angular Using the Angular CLI


      Introduction

      Angular is a popular JavaScript framework that creates interactive web, mobile, and desktop applications. Enforced separation of concerns, first-class TypeScript support, and robust Command Line Interface (CLI) make Angular a top choice for modern enterprise applications.

      The Angular CLI simplifies the process of getting started with Angular. The CLI also takes care of code generation, production builds, and dependency management.

      By the end of this tutorial, you’ll have created an Angular application with the Angular CLI. You’ll use the CLI to create a new app, run it in the browser, and build for production.

      You’ll also view how Angular splits presentation, styling, and business concerns into separate units. This involves practicing how HTML, CSS, and TypeScript layers interact with each other.

      Prerequisites

      To follow along with the article, you’ll need the following:

      Step 1 — Installing the Angular CLI and Creating Your First Application

      In this step, you’ll install the Angular CLI on your local computer and build out your Angular application. To begin, you’ll download the Angular CLI and achieve the following three goals:

      • Create a new Angular project

      • Run the local development server

      • Build this application for production

      Run the following command in your terminal to download the Angular CLI:

      • npm install -g @angular/cli

      To ensure the installation was successful, run the following command in your terminal:

      The Angular CLI will print the current version and surrounding environment to the terminal:

      Output

      Angular CLI: 12.1.4 Node: 14.17.4 Package Manager: npm 6.14.14 OS: darwin x64

      To begin working with Angular, you’ll create your first workspace with the CLI called my-first-angular-app. Projects in Angular are known as workspaces.

      Run the following in your terminal:

      • ng new my-first-angular-app

      The command will ask some initialization questions used to configure the workspace:

      Output

      ? Would you like to add Angular routing? (y/N) N ? Which stylesheet format would you like to use? ❯ CSS SCSS [ https://sass-lang.com/documentation/syntax#scss ] Sass [ https://sass-lang.com/documentation/syntax#the-indented-syntax ] Less [ http://lesscss.org

      For the first question, type in N as you won’t use Angular routing for this project. Press your ENTER or RETURN key.

      In the second question, select CSS as the stylesheet format.

      Press your ENTER or Return key to initialize your project.

      You’ll now have an Angular workspace named my-first-angular-app. The Angular CLI installs any required dependencies on project creation. For more information about the Angular CLI and workspace creation, check out the [Angular documentation]((https://angular.io/cli)).

      Now that you’ve downloaded the Angular CLI and made a new Angular workspace, let’s look at how to run your application in the browser.

      Step 2 — Running Your Angular Application in the Browser

      In this step, you’ll run your application in the browser using the CLI. Angular’s local development server refreshes the browser whenever the filesystem changes. The fast feedback cycle ensures that you can see the results of your changes as soon as possible.

      Angular’s local development server provides you with the following benefits:

      • Starts a local web server on a port of your choice.
      • Watch for changes in the files and reload the browser on change.
      • Manages TypeScript compilation and bundling.

      Ensure you’re in the my-first-angular-app directory by running this command in your terminal:

      Next, start the web server by running the following command in your terminal:

      Angular will build your development application and expose it on a local web server at http://localhost:4200. The application will open in a web browser because you added the -o flag to ng serve.

      You can verify that this was successful by examining the output of your terminal:

      Output

      ✔ browser application bundle generation complete. Initial Chunk Files | Names | Size vendor.js | vendor | 2.08 MB polyfills.js | polyfills | 128.57 kB main.js | main | 10.81 kB runtime.js | runtime | 6.59 kB styles.css | styles | 179 bytes | Initial Total | 2.22 MB Build at: 2021-08-01T23:30:14.012Z - Hash: 3302767a539a29a592de - Time: 7433ms ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** ✔ Compiled successfully.

      You can pass other configuration options to ng serve to customize the environment. You can see a complete list of configuration options here.

      You’ll now see your Angular application on the screen. As long as ng serve is running, any changes to the file system will cause the browser to update with the new content. Keep ng serve running throughout the development process of your application.

      In this step, you ran your Angular application in the browser using ng serve. You passed configuration options to CLI commands, such as `ng serve -o’.

      Next, you’ll make changes to an Angular component and see the changes reflected on the screen.

      Step 3 — Updating the Homepage Template

      In this step, you’ll be displaying content on-screen by editing HTML. The HTML template is otherwise known as the view of an Angular component. By the end of this step, you’ll have learned how to update the starter template with your content.

      You can find the HTML for your AppComponent at src/app/app.component.html. Open this up in a text editor of your choice and delete the contents. You should have a blank HTML document ready to write your markup.

      Add the below HTML copy to your src/app/app.component.html:

      src/app/app.component.html

      <div>
       <article>
        <header>
          <h1>I'm learning Angular at DigitalOcean</h1>
        </header>
        <section>
          <p>Here's what I've learned so far:</p>
          <ul>
            <li>
              Angular allows us to create performant web applications using TypeScript.
            </li>
            <li>
              I can use the Angular CLI to create/interact with my Angular workspace.
            </li>
            <li>
              Making changes will automatically be shown on screen, thanks to the local development server!
            </li>
          </ul>
        </section>
       </article>
      </div>
      

      You’ve added a <div> containing a header and a section that includes an unordered list. You will see your unordered list in bullet points and your title in large font due to the <h1> tag.

      Notice that your app component updates as soon as you save the document. Feel free to experiment with further additions of your own and witness them in real-time.

      You’ve now updated the HTML template of the base app component. This is the entry component for your Angular application. In the next step, you’ll be styling the content using CSS.

      Step 4 — Updating the Homepage Styling

      In this step, you’ll style your application with CSS. Angular allows you to work with both scoped and global styles. The ability to scope CSS to a component enables flexibility without impeding your designs.

      You’ll start by setting up some default global styles for your application by editing src/styles.css:

      src/app/app.component.css

       body { background-color: #fce7f3;
       display: flex;
       align-items: center;
       justify-content: center;
       height: 100vh;
       font-size: 2rem;
      }
      

      These styles centers all of your content in the middle of the screen, and sets a warm background color. Keep in mind that any changes made to your global styles.css will show in every component going forward. If successful, you will view the following in your browser:

      Global styling

      Note: Remember to save your files after each change before moving to the next step.

      The Angular CLI adds styles.css to the styles array of the build builder in your angular.json file. You don’t have to manually add a reference to styles.css to index.html.

      angular.json

      {
       "projects": {
       "my-first-angular-app": {
       ...
       "architect": {
       "build": {
       "builder": "@angular-devkit/build-angular:browser",
       "options": {
       ...
       "styles": ["src/styles.css"]
                }
              }
            }
          }
        }
      }
      

      You’ll review more about the Angular build process in Step 6.

      Next, let’s style the app component. Styles added to a component won’t appear in other parts of your application. For more information on style scoping, read through the Angular documentation.

      Head over to src/app/app.component.css and add the following CSS below the global style:

      src/app/app.component.css

      ... article {
       background-color: #fbcfe8;
       padding: 2rem 4rem;
       color: #1f2937;
       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
       box-shadow: 20px 20px 0px #db2777;
       border: 6px solid #831843;
       border-radius: 2rem;
      }
      
      header {
       text-decoration: underline;
      }
      
      ul {
       list-style: square;
      }
      

      Your style will now appear in the content within the <article> tag in your browser:

      Component styling

      With your styling in place, let’s explore how to change your user interface dynamically.

      Step 5 — Updating the Homepage TypeScript

      In this step, you’ll work with TypeScript in your Angular application, found at src/app/app.component.ts. Angular uses decorators to dynamically style your components with ngStyle and ngClass.

      Angular components use the JavaScript class syntax. To tell Angular that this class is a component, you’ll need to add a @Component(...) decorator to the class.

      Decorators in TypeScript and Angular provide metadata around the class or function declaration. In Angular, they are specifically used to provide metadata to the dependency injection system and the compiler. This allows arbitrary code to run before, during, and after executing a class or function. Angular then associates the files that connect with a component. You can find more information about decorators in TypeScript here.

      You can see this in action in the AppComponent created with the CLI. Open src/app/app.component.ts and observe the following:

      src/app/app.component.ts

      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
       ...
      }
      

      Notice that the styleUrls property is an array with one value. This is because app-root contains one CSS style sheet. You could add more style sheets to the styleUrls array, and Angular will bundle them together.

      The selector is the CSS selector that identifies this component. This will be the name of the component in the HTML template, and you can see this inside of index.html:

      index.html

      <!doctype html>
        <html lang="en">
          <head>
            ...
          </head>
          <body>
            <app-root></app-root>
          </body>
      </html>
      

      Angular allows you to bind application state defined inside of your src/app/app.component.ts file to its HTML template at src/app/app.component.html.

      Within the AppComponent, create a new variable named myNextProject and assign it the value of a porfolio website:

      src/app/app.component.ts

      import { Component } from '@angular/core';
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
        myNextProject="a portfolio website.";
      }
      

      You can now use the variable as a binder to src/app/app.component.html and connect the data defined in TypeScript to your HTML template. Angular defines TypeScript variables in HTML by surrounding the variable inside double curly braces:

      {{ myNextProject }}
      

      Within src/app/app.component.html, add the variable in the text between the <footer> tag:

      src/app/app.component.html

      <article>
        <header>
          <h1>I'm learning Angular at DigitalOcean</h1>
        </header>
        <section>
          <p>Here's what I've learned so far:</p>
          <ul>
          <li>
            Angular allows you to create performant web applications using TypeScript.
          </li>
          <li>
            I can use the Angular CLI to create/interact with my Angular workspace.
          </li>
          <li>
            Making changes will automatically be shown on screen, thanks to the local development server!
          </li>
        </ul>
       </section>
       <footer>
          <p>For my next project, I'll be making {{ myNextProject }}</p>
       </footer>
      </article>
      

      The content within the <p> tag will render as For my next project, I'll be making a portfolio website. in the browser:

      Binding to template variables

      As executed here, binding values in your template allows you to serve dynamic content to your users.

      You can also use functions inside of your TypeScript file to determine your outputs as well. In your src/app/app.component.ts, define a new variable showPurpleBoxShadow and a getBoxShadow() function:

      src/app/app.component.ts

      import { Component } from '@angular/core';
      
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
        myNextProject="a portfolio website.";
      
        showPurpleBoxShadow = true;
      
       get boxShadow() {
       if (this.showPurpleBoxShadow) return '20px 20px 0px #bdb2ff';
      
       return '20px 20px 0px #DB2777';
        }
      }
      

      Navigate to your src/app/app.component.html file and insert the [ngStyle] directive within your <article> tag:

      src/app/app.component.html

      <article [ngStyle]="{'box-shadow': boxShadow}">...</article>
      

      ngStyle is an Angular directive that binds application state to CSS styles. In Angular, a directive is a “marker” on a DOM element, such as [ngStyle]. Angular is then able to attach functionality to the DOM element.

      In this scenario, you’re applying different box-shadow styles depending on the value of showPurpleBoxShadow. You can also achieve the same result with the use of the ngClass directive. Instead of applying CSS styles, this will conditionally apply a CSS class.

      Open src/app/app.component.css and add the following CSS classes:

      src/app/app.component.css

      .purple-box-shadow {
       box-shadow: 20px 20px 0px #bdb2ff;
      }
      
      .pink-box-shadow {
       box-shadow: 20px 20px 0px #db2777;
      }
      

      Then, in src/app/app.component.ts, update the boxShadow getter to return a class name instead:

      src/app/app.component.ts

      export class AppComponent {
       ...
      
       get boxShadow() {
       if (this.showPurpleBoxShadow) return 'purple-box-shadow';
      
       return 'pink-box-shadow';
        }
      }
      

      You can then use the ngClass directive to conditionally apply the purple-box-shadow class to the <article> tag:

      src/app/app.component.html

      <article [ngClass]="boxShadow">
      ...
      </article>
      

      If successful, you will view the following in your browser:

      Dynamic styling with ngClass

      You can now see your design manifest on-screen without additional redeployment after each change. Let’s look at how to build your Angular application for development and production.

      Step 6 — Building Your Production Environment

      In this step, you’ll use the Angular CLI to generate a production build for your Angular project. Angular uses Webpack, which you will use to bundle your files and optimize the site for production.

      Webpack is an open-source module bundler for JavaScript applications. It provides the ability to load code/assets on demand. It offers a powerful optimization system that minimizes the number of requests needed to fetch all necessary assets from the server.

      To create a custom Webpack configuration file, review the article How To Use Custom webpack Configurations with Angular CLI Builders for more information.

      By default, the Angular CLI offers two types of builds:

      Development

      The unoptimized version of your code containing source maps and runtime checks that help you detect and investigate issues while developing an app before deploying it into production environments.

      The Angular CLI will generate an unoptimized version of your code when you run the command ng serve. You should avoid deploying the development build into production. The development build doesn’t contain any optimizations that are necessary for a fast, production-ready application.

      You can build your project with the development configuration by running the following command in your terminal:

      • ng build --configuration development

      Production

      Building your project with the production configuration will generate optimized code and provides you with benefits like:

      • Code minification and bundling to decrease your application’s size.
      • Tree-shaking to make unused parts of imported modules excluded from final builds, saving bandwidth with no detrimental impact on functionality.
      • No source maps, compiler errors, and warnings for a smaller bundle size.

      Production builds are essential for public-facing applications, as page speed and delivery time are crucial metrics for search engines and users. For more information on page speed and delivery time optimization, click here.

      To generate a production build, run ng build from your project folder. The CLI will lint your code and generate an optimized, minified version of your application.

      If successful, it’ll provide you with statistics about the bundle:

      Output

      ✔ browser application bundle generation complete. ✔ Copying assets complete. ✔ Index html generation complete. Initial Chunk Files | Names | Size main.0deeec3d31917b111ae5.js | main | 104.77 kB polyfills.313e64a67eb403254da5.js | polyfills | 35.96 kB runtime.284ffbeed756735f6289.js | runtime | 1.02 kB styles.e5294562d7aae78a8725.css | styles | 113 bytes | Initial Total | 141.86 kB

      Notice how the file names have a unique hash after their name. Angular adds this to allow for “cache-busting”. As the hash changes on each build, browsers can reset their cache when they revisit the site.

      If you make any changes to the file, the hash will change, and the browser will reload the new file. Otherwise, the browser will use the cached version.

      The Angular CLI can also show warnings at this stage when the bundle size is too large. You should continue to review bundle sizes as your application grows.

      You can find the configuration options that correspond to the Angular CLI commands, such as ng build and ng serve, in the angular.json file. Navigate through the configurations key to view the options set for the production and development builds. You can configure these limits on a per-build basis.

      angular.json

      {
       ...
       "projects": {
       "my-first-angular-app": {
       "architect": {
       "build": {
       ...
       "configurations": {
       "production": {
       "budgets": [
       {
        "type": "initial",
        "maximumWarning": "500kb",
        "maximumError": "1mb"
       },
       {
        "type": "anyComponentStyle",
        "maximumWarning": "2kb",
        "maximumError": "4kb"
       }
      ],
                  }
                }
              }
            }
          }
        }
      }
      

      The ng build command outputs these to the dist/my-first-angular-app folder to access the built files for deployment. You can use these files to deploy the application to a server or CDN. For more information on this, see the Angular CLI documentation.

      In this step, you learned how to use the Angular CLI to create a development and production build. You also considered important factors that go into producing a performant web application, such as bundle size.

      Conclusion

      In this tutorial, you created an Angular project using the Angular CLI. You excecuted and ran the project in the browser, and updated the way the application looks and performs.

      You used the CLI to generate a production build and learned about configuration options for a deeper insight into how and where the CLI operates.

      To learn more about the Angular CLI and additional commands, check out the Angular CLI documentation.



      Source link

      How To Generate a Vue.js Single Page App With the Vue CLI


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

      Introduction

      Vue.js is a popular JavaScript framework for creating user interfaces. Created in 2014 by Evan You (formally of Google), Vue.js is often described as a combination of React and Angular, borrowing the prop-driven development of React and the templating power of Angular. This makes Vue an accessible framework for beginners to pick up, especially since it focuses on traditional HTML and CSS, rather than being a CSS-in-JS framework like React or relying on TypeScript (a superset of JavaScript) like Angular does.

      When starting a new project, it’s best to familiarize yourself with the technology’s tools and features. One important tool for Vue.js development is its command line interface (CLI) known as Vue CLI 3. The Vue CLI offers a number of useful features that enhance the Vue development experience, but the main feature is its ability to generate and pre-configure a new single-page application with the vue create command.

      By the end of this tutorial, you will have a working Vue.js application running on a local Node server. This local server uses hot module reloading via Webpack to provide immediate feedback, rendered in-browser as you work. Along the way, you will create .vue single-file components (SFC), such as a header and a footer. All of this you can save as a solid foundation for any future Vue projects.

      Prerequisites

      To follow this tutorial, you will need the following:

      Step 1 — Downloading Vue CLI 3

      To download Vue CLI 3, you will need to run a command either via npm or Yarn, whichever you prefer. npm or Node Package Manager is a way to download and manage other people’s code to use in your project as a dependency. Yarn, on the other hand, executes NPM commands under the hood but provides additional features like caching. It’s up to personal preference regarding which one to use. However, it is important to note that it’s not recommended to mix commands. It’s best to be consistent with one or the other for the duration of your project.

      Moving forward, this tutorial will use npm commands. The following command will download the necessary Vue CLI files from the registrar, which in this case is the npm (Node Package Manager) service:

      npm i -g @vue/cli
      

      Note: On some systems, installing an npm package globally can result in a permission error, which will interrupt the installation. Since it is a security best practice to avoid using sudo with npm install, you can instead resolve this by changing npm’s default directory. If you encounter an EACCES error, follow the instructions at the official npm documentation.

      You install this globally in order to use the CLI anywhere on your machine. If you don’t install this globally, it will only work in the directory that you installed it at. In the case of the command options, i means “install” and -g is a flag to install the code globally on your computer.

      To verify if Vue CLI 3 was properly installed, run the following:

      vue --version
      

      You will receive the following output with a version number. Your version number may differ, but if you receive a response with a version number, you’ve properly installed Vue CLI 3:

      Output

      @vue/cli 4.5.6

      To update Vue CLI 3, run the previous commands in this section, and the latest version will be installed.

      At this point, you have successfully downloaded npm globally along with the Vue CLI tool that you will use in the next section to create a generated Vue.js project.

      Step 2 — Generating a Single-Page Application

      As you develop Vue.js applications, you may find that manually configuring a project is not the most productive use of your time, since configuring a new Vue.js project from scratch can take hours. This is the true power of Vue CLI: It provides you with a pre-generated template that is based on your specifications. Because of this, it’s already configured so you can start developing your website or application right away. Vue CLI 3 will ask you a few questions via a command line prompt about your project, download the required files, and pre-configure it for you so you are ready to work as soon as it’s done.

      To generate a single-page application, navigate to the directory you’d like your Vue project in, then run the following:

      vue create vue-starter-project
      

      The highlighted section of the command is the name of the root directory of the project. This will be the name of the folder that contains all of your Vue.js project files. This can be whatever you’d like, but in the case of this tutorial, you will use vue-starter-project.

      Once you type out that command, continue by pressing Enter. You will then receive the following prompt:

      Vue CLI v4.5.6
      ? Please pick a preset: 
        Default ([Vue 2] babel, eslint) 
        Default (Vue 3 Preview) ([Vue 3] babel, eslint) 
      ❯ Manually select features 
      

      If you do not want to configure your project and opt for the defaults, you can do so with either Vue 2 or Vue 3. For the purpose of this tutorial though, it’s recommended to manually select your features. By selecting specific features, you will see how each option you selected was installed by the CLI.

      Select Manually select features with ENTER. Immediately you’ll receive a number of different options, including: Choose Vue version, TypeScript, Router, and Vuex. Notice that some of these items are already selected (the bubble is filled in). You may select as many or as few as you’d like. However, for this tutorial, select the following by pressing <space> on the entry:

      ...
       ◉ Choose Vue version
       ◉ Babel
       ◉ TypeScript
       ◯ Progressive Web App (PWA) Support
       ◉ Router
       ◉ Vuex
       ◉ CSS Pre-processors
       ◉ Linter / Formatter
      ❯◯ Unit Testing
       ◯ E2E Testing
      

      Once you have your options selected, press the ENTER key. The CLI will ask you further questions regarding each of the features you selected for your project, in order. The first question will ask which version of Vue you’d like to use: 2.x or 3.x. You’ll use Vue 3 for this tutorial, but you may want to use Vue 2 if you want greater support from the Vue Community:

      ...
      ? Choose a version of Vue.js that you want to start the project with 
        2.x 
      ❯ 3.x (Preview)
      

      The next question is regarding TypeScript integration. If you are not familiar with TypeScript, that’s alright. This option was intentionally selected to illustrate how Vue CLI 3 downloads what you defined as required for unique project. This tutorial will not use the class-style syntax, but will use Babel alongside TypeScript.

      When encountering the following, enter N:

      ...
      Use class-style component syntax? (y/N) N
      

      In the following prompt, enter Y:

      ...
      ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n) Y
      

      Next, Vue CLI will ask about history mode. History mode will make each route its own URL. This means you will not have the /#/ (hash) in your application’s URL. If you do use history mode, you will need a Node server to run your project. This is not a problem, because Vue CLI 3 provides you with a Node server.

      Type Y to answer yes to history mode:

      ...
      ? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) Y
      

      The next question is regarding CSS pre-processors such as Sass or LESS. A CSS pre-processor is CSS with added features like nesting and variables. The browser cannot read this, so when the project is built, Node will compile all of your SCSS or LESS code to traditional CSS. Since you are using Node to build your project, it’s recommended to select Sass/SCSS (with node-sass) as your pre-processor. Later on, you’ll add lang attributes in your .vue components to enable SCSS on a per component basis:

      ...
      ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): 
        Sass/SCSS (with dart-sass) 
      ❯ Sass/SCSS (with node-sass) 
        Less 
        Stylus 
      

      After that, you will receive some questions regarding the linter style. A linter is a program that evaluates your code as you develop your application. This linter can enforce a number of syntactical rules during development. In addition to this, your integrated development environment (IDE) can read this configuration file and format your code on save. This will keep your code consistent no matter who works on your project and what operating system or IDE a developer is using.

      For this tutorial, choose ESLint + Standard config:

      ...
      ? Pick a linter / formatter config: 
        ESLint with error prevention only 
        ESLint + Airbnb config 
      ❯ ESLint + Standard config 
        ESLint + Prettier 
        TSLint (deprecated) 
      

      This selects a set of rules for ESLint to enforce. These configurations include options like the use of trailing commas, semi-colons at the end of a line, or using const over var in JavaScript.

      The next option is selecting when you want ESLint to format your code. This can be either on save or when you commit your code to a service like GitHub, GitLab, or BitBucket. It’s recommended to select Lint on save so you can review any changes before committing to version control:

      ...
      ? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
      ❯◉ Lint on save
       ◯ Lint and fix on commit
      

      Once you select your lint features, Vue CLI will ask you about how you want to store these configurations, whether in dedicated files or in the package.json. It’s considered standard practive to store configurations in their own files for a few reasons. One, configurations are easier to share between projects this way, and two, you’ll be keeping your package.json as legible as possible by only defining the important information about your app:

      ...
      ? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
      ❯ In dedicated config files 
        In package.json
      

      Once you are done, the CLI tool will ask if you want to save this selection as a preset for future projects. This is useful if you are generating projects for your employer and you want everything to stay consistent.

      Go ahead and save this configuraion as a preset; Vue CLI will ask you to rename it. Name it DigitalOcean Vue Tutorial Series:

      ...
      ? Save this as a preset for future projects? Yes
      ? Save preset as: DigitalOcean Vue Tutorial Series
      

      Now you can use these exact same settings for a future project.

      At this point, you will have something along the lines of this in your terminal summarizing all of your options:

      ? Please pick a preset: Manually select features
      ? Check the features needed for your project: Choose Vue version, Babel, TS, Router, Vuex, CSS Pre-processors, Linter
      ? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
      ? Use class-style component syntax? No
      ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes
      ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
      ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
      ? Pick a linter / formatter config: Standard
      ? Pick additional lint features: Lint on save
      ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
      ? Save this as a preset for future projects? (y/N) 
      

      Press ENTER, and Vue CLI will start creating your app.

      When completed, cd (change directory) in your project name (vue-starter-project):

      Next, start the application with npm run serve. This will run your project at a port on your localhost, usually :8080. If it’s a different port, the CLI will tell you:

      npm run serve
      

      You do not need to download dependencies, as the CLI already did that for you. To view your generated project, open your browser of choice and visit localhost:8080 in the URL bar. You will find a welcome screen with the Vue logo and the technologies you’ve selected in the previous steps.

      Vue template screen

      You can leave this server running throughout this tutorial to monitor your changes.

      In this section, you selected a number of options specific to the project you are creating. Vue CLI downloaded all of the code needed and pre-configured it for you. You can now start working in the generated code base, including creating your own single-file .vue components.

      Now that you have a single-page application running on a Node server, make some changes to this by creating a standard header and footer. These AppHeader.vue and AppFooter.vue components will be imported in such a way that they’ll be present on each route.

      In a new terminal window, navigate into the root of your vue-starter-project folder and list out the files with the following command:

      You will receive the following output:

      Output

      README.md babel.config.js node_modules package-lock.json package.json public src tsconfig.json

      You can also view the contents of your project by opening your project in your editor of choice, such as Visual Studio Code. In either case, you will have access to a number of different files and directories. These config files in the root directory have been created because of the selections made during the intial generation of this project. The option In dedicated config files told Vue CLI to create config.js files for each service you are using, such as Babel, TypeScript, and ESLint. In addition to these files, there are a number of directories. This tutorial will go over these as you get to them.

      First, create a .vue file in the components directory and name it AppHeader.vue. You can do this right-clicking in the components directory and creating a new file in IDEs like VS Code. If you prefer terminal commands, you can do this in your computer’s terminal with the bash command touch:

      touch src/components/AppHeader.vue
      

      In this step, you are creating a single-file component that will contain all of the HTML, JavaScript, and SCSS that this chunk of code needs. Every .vue component contains three basic concerns or sections: <template>, <script>, and <style>. In this case, template is the component’s HTML.

      Open up the new file in your text editor.

      In this file, create a header by using the <header> tag inside of <template>. Inside of this <header>, add the Vue.js logo and a <p> element with the content My Vue.js Application:

      vue-starter-project/src/components/AppHeader.vue

      <template>
        <header>
          <img alt="Vue logo" src="https://www.digitalocean.com/community/tutorials/assets/logo.png" height="50">
          <p>My Vue.js Application</p>
        </header>
      </template>
      

      Keep your development server running throughout development. If you close or cancel the server process, you will not be able to view your application in the browser.

      Save the file.

      At this point, when you open your browser, you will not see the HTML rendered. That is because you need to import the newly created AppHeader.vue component into a component that is already mounted. Since App.vue is your main entry point, it’s best to import it there so our header appears on every route.

      Open up the App.vue file in your text editor, then delete the div with the ID of nav and add the following highlighted code:

      vue-starter-project/src/App.vue

      <template>
        <app-header />
        <router-view/>
      </template>
      
      <script>
      import AppHeader from '@/components/AppHeader.vue'
      
      export default {
        components: {
          AppHeader
        }
      }
      </script>
      

      When you import using ES6, you are essentially creating a variable to later reference in your code. In this case, you are storing the code from AppHeader.vue into a variable called AppHeader. You need to register it via the components property before you can use it.

      Once it’s imported, you deleted the #nav in the template and added <app-header /> before the <router-view />. This renders the component in the HTML.

      After completing this step, save any unsaved file and open your browser back to localhost:8080. Thanks to hot module reloading, you will now find your newly created header at the top of the page:

      Vue template with new header

      You’ve now created a single-file Vue component, used import to bring it into a mounted component, and monitored the change with hot module reloading (HMR). Moving forward, you will extend the functionality of components through the use of child components. You will also use SCSS (the pre-processor you selected earlier) on a per component basis with the lang attribute.

      Now that the header is imported properly into the application, return to AppHeader.vue in your text editor. Add navigation underneath <p>My Vue.js Application</p> by adding the following highlighted code:

      vue-starter-project/src/components/AppHeader.vue

      <template>
        <header>
          <img alt="Vue logo" src="https://www.digitalocean.com/community/tutorials/assets/logo.png" height="50">
          <p>My Vue.js Application</p>
          <nav>
            <ul>
              <li><router-link to="/">Home</router-link></li>
              <li><router-link to="/about">About</router-link></li>
            </ul>
          </nav>
        </header>
      </template>
      

      Now, style this to make it look more like a traditional navigation bar. Create a <style> tag at the end of the file.

      vue-starter-project/src/components/AppHeader.vue

      <template>
        <header>
          <img alt="Vue logo" src="https://www.digitalocean.com/community/tutorials/assets/logo.png" height="50">
          <p>My Vue.js Application</p>
          <nav>
            <ul>
              <li><router-link to="/">Home</router-link></li>
              <li><router-link to="/about">About</router-link></li>
            </ul>
          </nav>
        </header>
      </template>
      
      <style lang="scss">
      </style>
      

      During the inital setup, you selected the Sass/SCSS (with node-sass) option. This is why you added on the lang="scss" attribute to your style tag. If you are unfamiliar with SCSS, it’s recommended to view their official documentation for specifics on when to use nesting or variables.

      This lang attribute will give you the ability to write SCSS in your single-file component. Add the following highlighted contents in the style element:

      vue-starter-project/src/components/AppHeader.vue

      ...
      <style lang="scss">
        header {
          display: flex;
          border-bottom: 1px solid #ccc;
          padding: .5rem 1rem;
      
          p {
            margin-left: 1rem;
          }
        }
      
        nav {
          margin-left: auto;
      
          ul {
            list-style: none;
          }
      
          ul li {
            display: inline-flex;
            margin-left: 1rem;
          }
        }
      </style>
      

      This SCSS creates a horizontal navigation bar with declarations such as display: inline-flex (using Flexbox) and spaces each item out with margin-left auto. To separate the header from the rest of the content, some padding is applied with padding: .5rem 1rem along with a bottom border using border-bottom: 1px solid #ccc. You may notice that the p styles are inside of the header SCSS block. In traditional CSS, that is not allowed, but thanks for SCSS, you can do that. This is refered to as nesting. In this case, the p inside the header is the same as selecting header p in traditional CSS.

      Save your file and navigate to localhost:8080 in your browser to find the new style:

      New style for header in Vue template

      You now have created and styled your header component. Next, you will create the footer component.

      Now that you have a header, you will complete your example application with a footer. In the same components directory, create a new file with the name AppFooter.vue. The process of creating this component is the same as creating the AppHeader.vue. You can create the file in your editor or through the touch base command.

      touch src/components/AppFooter.vue
      

      As before, import this into your App.vue file. Open up App.vue and add the following highlighted code:

      vue-starter-project/src/App.vue

      <template>
        <app-header />
        <router-view/>
        <app-footer />
      </template>
      
      <script>
      import AppHeader from '@/components/AppHeader.vue'
      import AppFooter from '@/components/AppFooter.vue'
      
      export default {
        components: {
          AppHeader,
          AppFooter
        }
      }
      </script>
      ...
      

      This time, you’re importing the component after the router-view tag.

      Save the file, then open up AppFooter.vue. In your AppFooter.vue file, use the <footer> HTML tag with a paragraph:

      vue-starter-project/src/components/AppFooter.vue

      <template>
        <footer>
          <p>Copyright &copy; "current year" </p>
        </footer>
      </template>
      

      You now have a basic footer. Continue to expand on this to include the current year programmatically. This will be dynamic depending on what the year is. To achieve this, you will create a computed property. A computed property is a reactive value calculated with JavaScript.

      In Vue 3, you need to wrap your properties in the setup() function and return these values. Essentially, you are telling Vue to construct this component and provide the template to these reactive computed properties.

      To create a computed property, you’ll first need to deconstruct the computed function from the vue library. You will store this computed function and its value into a const. In Vue 3, you need to pass an anonymous function that returns a value:

      const year = computed(() => new Date().getFullYear())
      

      To add the setup function to your file, add the following script to the end of AppFooter.vue:

      vue-starter-project/src/components/AppFooter.vue

      ...
      <script>
      import { computed } from 'vue'
      
      export default {
        setup () {
          const year = computed(() => new Date().getFullYear())
        }
      }
      </script>
      

      After that, you will need to provide access to the computed property you created for the <template> to consume and render. Return an object with the year property and value in your setup() function:

      /vue-starter-project/src/components/AppFooter.vue

      ...
      setup () {
        const year = computed(() => new Date().getFullYear())
        return { year }
      }
      ...
      

      To use this value in the <template>, use interpolation with double curly braces. This is sometimes referred to the “moustache syntax”:

      /vue-starter-project/src/components/AppFooter.vue

      <template>
        <footer>
          <p>Copyright &copy; {{ year }}</p>
        </footer>
      </template>
      

      Save the file. You will now have the current year in your footer:

      Sample vue application with a computed header

      Conclusion

      In this tutorial, you downloaded the Vue CLI and created your own single-file components with AppHeader.vue and AppFooter.vue. You successfully generated a Vue.js Single Page Application (SPA) with selected features from the initial setup, and learned how all of those pieces come together. In addition, you’ve now reviewed the basic architecture of most SPAs and can use that knowledge to futher expand this project.

      Vue.js is a growing ecosystem with a number of tools at your disposable. These tools can help you quickly get started and save time by storing options as a preset. This is just the start of what Vue.js has to offer, but the CLI is perhaps one of the most important tools you will use in your Vue.js journey.

      For more information on Vue.js and Vue CLI 3, it’s recommended to read through their documentation. The CLI tool specifically has many additional features that weren’t covered in this tutorial. For more tutorials on Vue, check out the Vue Topic Page.



      Source link

      Using Sass with the Angular CLI


      One of the first things you’ll usually do in a project is to bring in Sass to make working with CSS easier.

      Angular CLI Home Page

      When working with the Angular CLI, the default stylesheets have the .css extension.

      <div class=“notification is-info m-b-md”>Related Video Course: <a href=“https://scotch.io/courses/working-with-the-angular-cli”>Working with the Angular CLI</a></div>

      Let’s explore how we can easily bring in Sass to our Angular CLI projects.

      Sass Home Page

      If you want a quick intro into the Angular CLI, check out the official docs and our Use the Angular CLI For Faster Angular v2+ Projects.

      Starting an Angular CLI Project with Sass

      Normally, when we run ng new my-app, our app will have .css files. To get the CLI to generate .scss files (or .sass/.less) is an easy matter.

      Create a new project with Sass with the following:

      ng new my-sassy-app --style=scss
      

      You can also set the --style flag with the following:

      • --style=scss
      • --style=sass
      • --style=less

      Converting a Current App to Sass

      If you’ve already created your Angular CLI app with the default .css files, it will take a bit more work to convert it over. You can tell Angular to start processing Sass files with the following command:

      ng set defaults.styleExt scss
      

      This will go ahead and tell the Angular CLI to start processing .scss files. If you want to peek under the hood at what this command did, check out the Angular CLI config file: .angular-cli.json.

      You’ll find the new config line at the bottom of the file:

      "defaults": {
        "styleExt": "scss",
        "component": {
        }
      }
      

      Changing the CSS Files to Sass

      The Angular CLI will start processing Sass files now. However, it doesn’t go through the process of converting your already existing .css files to .scss files. You’ll have to make the conversion manually.

      Using Sass Imports

      I personally like creating Sass files for project variables and for project mixins. This way, we can bring in any variables/mixins we’ll need quickly and easily.

      For instance, let’s create a brand new CLI app:

      ng new my-sassy-app --style=scss
      

      Next, we’ll create the following files:

      |- src/
          |- sass/
              |- _variables.scss
              |- _mixins.scss
              |- styles.scss
      

      To start using these new Sass files, we’ll import the _variables.scss and _mixins.scss into the main styles.scss.

      // src/sass/styles.scss
      
      @import './variables';
      @import './mixins';
      

      The last step is to update our .angular-cli.json config to use this new src/sass/styles.scss instead of the src/styles.scss. In our .angular-cli.json file, just change the following line to point to the right styles.scss.

      "styles": [
        "sass/styles.scss"
      ],
      

      I like separating out our Sass into its own folder because it allows us to create a more robust Sass foundation. I personally lean towards the Sass 7-1 Pattern.

      Now when we start up our app, these new Sass files will be used!

      Importing Sass Files Into Angular Components

      We have new _variables.scss and _mixins.scss files that we will probably want to use in our components. In other projects, you may be used to having access to your Sass variables in all locations since your Sass is compiled by a task runner.

      In the Angular CLI, all components are self-contained and so are their Sass files. In order to use a variable from within a component’s Sass file, you’ll need to import the _variables.scss file.

      One way to do this is to @import with a relative path from the component. This may not scale if you have many nested folders or eventually move files around.

      The CLI provides an easy way to import Sass files using the ~.

      No matter what component Sass file we’re in, we can do an import like so:

      // src/app/app.component.scss
      
      @import '~sass/variables';
      
      // now we can use those variables!
      

      The tilde (~) will tell Sass to look in the src/ folder and is a quick shortcut to importing Sass files.

      Sass Include Paths

      In addition to using the ~, we can specify the includePaths configuration when working with the CLI. To tell Sass to look in certain folders, add the config lines to .angular-cli.json like in the app object next to the styles setting.

      <div class=“notification is-info”>This is the recommended way to use Sass files in an Angular CLI app. It is better to be more explicit about where our files come from. We can do that with stylePreprocessorOptions.includePaths.</div>

      "styles": [
        "styles.scss"
      ],
      "stylePreprocessorOptions": {
        "includePaths": [
          "../node_modules/bootstrap/scss"
        ]
      },
      

      Using Bootstrap Sass Files

      Another scenario we’ll need to do often is to import third party libraries and their Sass files.

      We’ll bring in Bootstrap and see how we can import the Sass files into our project. This is good since we can pick and choose what parts of Bootstrap we want to use. We can also import the Bootstrap mixins and use them in our own projects.

      To get us started, install bootstrap:

      npm install --save bootstrap
      

      Note: We’re using the 4.0 beta because 4.0 is built with Sass and gives the proper .scss files.

      Adding Bootstrap CSS File

      Now that we have Bootstrap, let’s look at how we can include the basic CSS file. This is an easy process by adding the bootstrap.css file to our .angular-cli.json config:

      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "sass/styles.scss"
      ],
      

      Note: We’re using the .. because the CLI starts looking from within the src/ folder. We had to go up one folder to get to the node_modules folder.

      While we can import the Bootstrap CSS this way, this doesn’t let us import just sections of Bootstrap or use the Sass variables/mixins that Bootstrap provides.

      Let’s look at how we can use the Bootstrap Sass files instead of the CSS file.

      Adding Bootstrap Sass Files

      Let’s cut down the number of CSS rules that we use in our app. Let’s look at all the Sass files that Bootstrap uses:

      /*!
       * Bootstrap v4.0.0-beta (https://getbootstrap.com)
       * Copyright 2011-2017 The Bootstrap Authors
       * Copyright 2011-2017 Twitter, Inc.
       * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
       */
      
      @import "functions";
      @import "variables";
      @import "mixins";
      @import "print";
      @import "reboot";
      @import "type";
      @import "images";
      @import "code";
      @import "grid";
      @import "tables";
      @import "forms";
      @import "buttons";
      @import "transitions";
      @import "dropdown";
      @import "button-group";
      @import "input-group";
      @import "custom-forms";
      @import "nav";
      @import "navbar";
      @import "card";
      @import "breadcrumb";
      @import "pagination";
      @import "badge";
      @import "jumbotron";
      @import "alert";
      @import "progress";
      @import "media";
      @import "list-group";
      @import "close";
      @import "modal";
      @import "tooltip";
      @import "popover";
      @import "carousel";
      @import "utilities";
      

      That’s a lot of tools that you may not use in your own project.

      Inside our src/sass/styles.scss file, let’s import only the Bootstrap files we’ll need. Just like we imported Sass files from the src folder using the tilde (~), the tilde will also look into the node_modules folder.

      While we could use the tilde, since we already added Bootstrap to our include_paths in the stylePreprocessorOptions section of our .angular-cli.json:

      "styles": [
        "styles.scss"
      ],
      "stylePreprocessorOptions": {
        "includePaths": [
          "../node_modules/bootstrap/scss"
        ]
      },
      

      We can do the following to only get the Bootstrap base tools:

      // src/sass/styles.scss
      
      @import 
        'functions',
        'variables',
        'mixins',
        'print',
        'reboot',
        'type';
      

      Conclusion

      The tilde (~) and the ability to add paths to stylePreprocessorOptions.includePaths makes importing Sass files in the Angular CLI super easy! Hope this quick tip was helpful in your Angular journey. Thanks for reading.

      While it is easy to use the ~ in quick situations, I recommend using the includePaths method to be explicit about the exact folders where your .scss files live.



      Source link