javascriptroom guide

Getting Started with Vue.js and Vue CLI

Vue.js has rapidly become one of the most popular JavaScript frameworks for building interactive web applications. Known for its simplicity, flexibility, and gentle learning curve, Vue.js empowers developers to create everything from small widgets to large-scale SPAs (Single-Page Applications). While Vue.js can be used directly via a CDN for simple projects, **Vue CLI (Command Line Interface)** elevates the development experience by providing a standardized, pre-configured setup for Vue projects. It handles complex build processes (like bundling, transpilation, and optimization) out of the box, letting you focus on writing code rather than configuring tools like Webpack or Babel. In this blog, we’ll walk through everything you need to know to get started with Vue.js and Vue CLI, from installation to building your first production-ready app.

Table of Contents

  1. Prerequisites
  2. What is Vue CLI?
  3. Installing Vue CLI
  4. Creating Your First Vue Project
  5. Understanding the Project Structure
  6. Running the Development Server
  7. Modifying the App: Vue Single-File Components (SFCs)
  8. Building for Production
  9. Additional Vue CLI Features
  10. Troubleshooting Common Issues
  11. Conclusion
  12. References

Prerequisites

Before diving into Vue.js and Vue CLI, ensure you have the following tools installed:

  • Node.js: Vue CLI requires Node.js (v8.9 or later, but v14+ recommended for stability). Node.js includes npm (Node Package Manager), which we’ll use to install dependencies.
  • npm: Included with Node.js. Verify installation by running:
    node -v  # Should output a version like v18.17.1  
    npm -v   # Should output a version like 9.6.7  

What is Vue CLI?

Vue CLI is a standardized tooling baseline for Vue.js development. It abstracts away complex build configurations (Webpack, Babel, ESLint, etc.) and provides:

  • A pre-configured development environment with hot-reload (instant updates when you edit code).
  • Optimized production builds (minification, code splitting, tree-shaking).
  • Plugin-based architecture to extend functionality (e.g., adding Vue Router, Vuex, or TypeScript).
  • A graphical user interface (GUI) for managing projects (via vue ui).

Installing Vue CLI

Vue CLI is installed globally via npm. Open your terminal and run:

npm install -g @vue/cli  

Note for macOS/Linux users: If you get a “permission denied” error, prefix the command with sudo:

sudo npm install -g @vue/cli  

Alternatively, use nvm (Node Version Manager) to avoid permission issues.

Verify installation by checking the version:

vue --version  # Should output a version like @vue/cli 5.0.8  

Creating Your First Vue Project

With Vue CLI installed, let’s create a new project. Run:

vue create my-first-vue-app  

Step 1: Select a Preset

Vue CLI will prompt you to choose a preset:

  • Default (Vue 3): Includes Vue 3, Babel, and ESLint (recommended for beginners).
  • Default (Vue 2): For legacy projects using Vue 2.
  • Manually select features: Customize tools like TypeScript, Vue Router, Vuex, CSS pre-processors, etc.

For this tutorial, select Default (Vue 3) and press Enter.

Step 2: Wait for Dependencies to Install

Vue CLI will create a project folder (my-first-vue-app) and install dependencies. This may take a minute or two.

Understanding the Project Structure

Once the project is created, navigate into the folder:

cd my-first-vue-app  

Let’s explore key files and directories:

my-first-vue-app/  
├── node_modules/       # Dependencies (auto-generated)  
├── public/             # Static assets (e.g., index.html, favicon.ico)  
│   ├── index.html      # HTML template (Vue mounts here)  
│   └── favicon.ico     # App icon  
├── src/                # Source code (your app lives here)  
│   ├── assets/         # Images, fonts, etc. (processed by Webpack)  
│   ├── components/     # Reusable Vue components  
│   │   └── HelloWorld.vue  # Default example component  
│   ├── App.vue         # Root component (entry point for your app)  
│   └── main.js         # Main JavaScript file (mounts Vue to the DOM)  
├── .gitignore          # Files to ignore in Git  
├── package.json        # Project metadata and scripts  
└── README.md           # Project documentation  

Understanding the Project Structure

Let’s break down the most important files:

src/main.js

The entry point of your app. It initializes Vue and mounts the root component (App.vue) to the DOM:

import { createApp } from 'vue'  
import App from './App.vue'  

createApp(App).mount('#app')  // Mounts App.vue to the <div id="app"> in public/index.html  

src/App.vue

The root component of your app, written as a Vue Single-File Component (SFC). SFCs combine HTML, JavaScript, and CSS in one file:

<template>  
  <!-- HTML template -->  
  <img alt="Vue logo" src="./assets/logo.png">  
  <HelloWorld msg="Welcome to Your Vue.js App"/>  
</template>  

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

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

<style>  
/* CSS styles (scoped to this component by adding 'scoped' attribute) */  
#app {  
  font-family: Avenir, Helvetica, Arial, sans-serif;  
  -webkit-font-smoothing: antialiased;  
  -moz-osx-font-smoothing: grayscale;  
  text-align: center;  
  color: #2c3e50;  
  margin-top: 60px;  
}  
</style>  

public/index.html

The HTML template where your Vue app is injected. The <div id="app"></div> is the mount point referenced in main.js.

Running the Development Server

To preview your app locally, run:

npm run serve  

Vue CLI will start a development server at http://localhost:8080. Open this URL in your browser—you’ll see a default Vue welcome page!

Hot Reload: Edit any file (e.g., src/components/HelloWorld.vue), and the browser will auto-update without refreshing.

Modifying the App: Vue Single-File Components (SFCs)

Let’s customize the HelloWorld component to learn core Vue concepts. Open src/components/HelloWorld.vue and replace its content with:

<template>  
  <div class="hello">  
    <h1>{{ message }}</h1>  
    <input v-model="name" placeholder="Enter your name">  
    <p v-if="name">Hello, {{ name }}!</p>  
    <button @click="count++">Click me: {{ count }}</button>  
  </div>  
</template>  

<script>  
export default {  
  name: 'HelloWorld',  
  data() {  // Reactive data properties  
    return {  
      message: 'Hello from Vue!',  
      name: '',  
      count: 0  
    }  
  }  
}  
</script>  

<style scoped>  
/* 'scoped' ensures styles only apply to this component */  
.hello {  
  max-width: 600px;  
  margin: 0 auto;  
  padding: 20px;  
}  
input {  
  padding: 8px;  
  margin: 10px 0;  
  width: 200px;  
}  
button {  
  padding: 8px 16px;  
  background: #42b983;  
  color: white;  
  border: none;  
  border-radius: 4px;  
  cursor: pointer;  
}  
</style>  

Key Concepts Demonstrated:

  • {{ }} (Mustache Syntax): Renders reactive data (e.g., {{ message }}).
  • v-model: Two-way data binding (updates name when the input changes, and vice versa).
  • v-if: Conditionally renders content (shows “Hello, [name]!” only if name is not empty).
  • @click: Event listener (increments count when the button is clicked).
  • data(): Returns an object of reactive properties (Vue tracks changes to these and updates the DOM).

Building for Production

When your app is ready for deployment, build an optimized production version with:

npm run build  

This generates a dist/ folder containing:

  • Minified HTML, CSS, and JavaScript.
  • Optimized assets (images, fonts) with hash filenames (to avoid caching issues).
  • Code splitting (only loads necessary code for each page).

The dist/ folder is ready to deploy to any static hosting service (e.g., Netlify, Vercel, GitHub Pages, or a traditional web server like Nginx).

Additional Vue CLI Features

1. Adding Plugins Later

If you initially chose the “Default” preset but want to add features like Vue Router (for navigation) or Vuex (state management), use:

vue add router  # Adds Vue Router  
vue add vuex    # Adds Vuex  

2. Graphical User Interface (GUI)

Vue CLI includes a GUI for managing projects. Run:

vue ui  

This opens a browser window at http://localhost:8000 where you can:

  • Create/import projects.
  • Install plugins.
  • Run scripts (serve, build).
  • View project stats (bundle size, dependencies).

Troubleshooting Common Issues

”vue: command not found”

  • Ensure Vue CLI is installed globally: npm install -g @vue/cli.
  • Check your npm global path: npm config get prefix—add this path to your system’s PATH environment variable.

Project Fails to Run (npm run serve)

  • Delete node_modules and package-lock.json, then reinstall dependencies:
    rm -rf node_modules package-lock.json  
    npm install  
  • Ensure you’re using a supported Node.js version (Vue CLI 5+ requires Node.js 14.18+).

Conclusion

You’ve now learned the basics of Vue.js and Vue CLI: installing tools, creating projects, understanding the structure, running a development server, modifying components, and building for production.

Vue.js’s simplicity and Vue CLI’s tooling make it easy to scale from small apps to large SPAs. Next steps: explore Vue Router for navigation, Vuex/Pinia for state management, and TypeScript for type safety.

References