Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

A Quick Guide to Setting Up Projects with Vue CLI 3.0

Tech May 16 1

Vue CLI represents a comprehensive framework designed for accelerated Vue.js development. The system comprises three primary components that work together to streamline your workflow:

CLI Package: The @vue/cli package installs globally via npm and provides terminal commands such as vue create, vue serve, and vue ui for project initialization and management.

CLI Service: The @vue/cli-service package serves as a development dependency built on top of webpack and webpack-dev-server. It provides essential commands including serve for development servers, build for production bundles, and inspect for configuration analysis.

CLI Plugins: Optional npm packages that extend Vue projects with additional functionality such as Babel/TypeScript transpilation, ESLint integration, and unit/e2e testing capabilities.

Installation

Prerequisite Cleanup: If you have an older version of vue-cli (1.x or 2.x) installed globally, remove it first to avoid conflicts:


npm uninstall vue-cli -g
# or
yarn global remove vue-cli

Node.js Requirement: Vue CLI 3 requires Node.js version 8.9 or higher. The official recommendation is version 8.11.0 or later. If you need to manage multiple Node versions on the same machine, consider using nvm (or nvm-windows for Windows systems).

Download Node.js: Visit the official download page at https://nodejs.org/ to obtain the latest version for your operating system.

Install Vue CLI: The package name changed from vue-cli to @vue/cli in version 3:


npm install -g @vue/cli
# or
yarn global add @vue/cli

Verify the installation by checking the version:


vue --version

Creating a New Project

Command-Line Approach: Use the vue create command to initialize a new project. Note that project names cannot use camelCase as they are converted to kebab-case for file system compatibility:


vue create project-name

Git Bash Consideration: Windows users running Git through minTTY should use winpty vue.cmd create project-name instead, as interactive prompts may not display correctly otherwise.

After executing the command, you'll be prompted to select a preset configuration. The interface displays previously saved presets (if any), followed by two default options:

The default preset provides a minimal setup with Babel and ESLint. This option works well for rapid prototyping but includes no additional npm packages for routing, state management, or testing.

Selecting Manually select features (using the arrow keys) opens a comprehensive configuration menu where you can customize your project setup for production use.

Feature Selection

Press the spacebar to toggle each feature, 'a' to select all options, or 'i' to invert the current selection:


? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
(*) Babel - Transpiler that converts ES6+ code to ES5 for broader browser compatibility
(*) TypeScript - Superset of JavaScript requiring compilation to plain JS before browser execution
(*) Progressive Web App (PWA) Support - Enables offline-capable web applications
(*) Vue Router - Official routing library for single-page applications
(*) Vuex - State management pattern and library for Vue applications
(*) CSS Pre-processors - Sass, Less, or Stylus for enhanced CSS development
(*) Linter / Formatter - ESLint or similar tools for code quality enforcement
(*) Unit Testing - Jest, Mocha, or other frameworks for component-level testing
(*) E2E Testing - Cypress, Nightwatch, or similar for end-to-end integration testing

After selecting your desired features, the CLI prompts for additional configuration details specific to each choice.

Router Mode Selection

Choose whether to use history mode for routing. This mode utilizes the browser's History API for clean URLs without hash fragments, requiring proper server configuration for SPA routing fallback.

CSS Preprocessor Choice

Select your preferred CSS preprocessing tool. Options typically include Sass/SCSS, Less, or Stylus. Consider team familiarity and existing codebases when making this decision.

Code Linting Configuration

Select a linter/formatter combination. Popular choices include ESLint with Prettier for unified code formatting standards across your codebase.

Testing Framework Selection


? Pick a unit testing solution: (Use arrow keys)
> Jest - Simple configuration, built-in coverage reports, seamless Babel integration
  Mocha + Chai - Flexible framework requiring additional plugins for comprehensive testing features

Configuration File Placement

Decide whether to store configuration in dedicated files or within package.json. Dedicated configuration files typically offer better version control and readability for larger projects.

Save Preset: Optionally save your current configuration as a named preset for future projects, eliminating repetitive setup steps.

Project Structure Comparison

Vue CLI 3 introduced significant structural changes compared to version 2, streamlining the codebase while maintaining core functionality.

State Management (Vuex)

Vue CLI 2 Appproach: Vuex installation occurred separately after project creation. The default store directory contained three files: actions.js for asynchronous API calls, mutations.js for synchronous state modifications, and index.js for store initialization.

Vue CLI 3 Approach: Vuex appears as an optional feature during project setup. The framework consolidates the store into a single store.js file, reducing boilerplate while preserving action, mutation, and getter functionality.

Routing Configuration

Vue CLI 2 used a router/index.js file structure, while Vue CLI 3 consolidaets this to router.js. The underlying functionality remains identical, with only the file location changing.

Static Asset Handling

Vue CLI 2: The static directory served as webpack's default location for unprocessed static assets. Files placed here were copied directly to the dist folder without compilation.

Vue CLI 3: The static folder replaced with a public directory offering two distinct asset handling strategies:

Webpack-Processed Assets: Resources referenced through JavaScript imports, template paths, or CSS relative URLs undergo compilation, minification, and optimization.

Public Directory Assets: Files in the public folder or referenced via absolute paths bypass webpack processing entirely, copied directly to the output directory without modificasion.

HTML Template Location

Vue CLI 2 placed index.html at the project root. Vue CLI 3 moves this template to public/index.html, where it receives processing from the html-webpack-plugin for proper script injection.

View Directory Addition

The src folder in Vue CLI 3 projects includes a dedicated views directory for page-level components, creating a clear separation from reusable components stored in the components directory.

Build and Configuration Folders

Vue CLI 2 maintained separate build and config folders for webpack configuration. Vue CLI 3 eliminates these directories, consolidating settings into vue.config.js or CLI arguments. The devServer configuration, for example, now resides within vue.config.js rather than a separate config file.

Babel Configuration

Vue CLI 3 employs babel.config.js using Babel 7's configuration format. Unlike .babelrc or babel fields in package.json (which apply configurations based on file location), this format consistently applies transformations throughout the entire project, including node_modules dependencies. The Vue CLI documentation recommends using babel.config.js for all Vue CLI projects.

Configuration with vue.config.js

Create a vue.config.js file in your project root to customize build behavior. This file centralizes all configuration options that were previously scattered across multiple files in Vue CLI 2:


module.exports = {
  baseUrl: '/',
  outputDir: 'dist',
  assetsDir: '',
  indexPath: 'index.html',
  pages: {
    index: {
      entry: 'src/main.js',
      template: 'public/index.html',
      filename: 'index.html',
      title: 'Application Home',
      chunks: ['chunk-vendors', 'chunk-common', 'index']
    }
  },
  lintOnSave: true,
  productionSourceMap: true,
  css: {
    extract: true,
    sourceMap: false,
    loaderOptions: {},
    modules: false
  },
  devServer: {
    host: 'localhost',
    port: 8080,
    https: false,
    hotOnly: false,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:4000',
        ws: true,
        changeOrigin: true
      }
    }
  },
  pluginOptions: {}
};

This configuration file consolidates settings that previously required multiple config files. Understanding vue.config.js thoroughly proves essential for effective Vue CLI 3 project management.

Hot Module Replacement Configuration

Enhance hot reload functionality by adding the following to your vue.config.js:


module.exports = {
  chainWebpack: config => {
    config.resolve.symlinks(true);
  },
  css: {
    // extract: false
  }
};

Setting extract: false in the CSS configuration ensures that style updates propagate immediately during development, eliminating the need for full page refreshes when modifying styles.

Graphical Interface

Vue CLI includes a visual project manager accessible via the command:


vue ui

This web-based interface provides an intuitive alternative to command-line project creation. Users can initialize projects, manage dependencies, install plugins, and adjust configuration settings through a graphical dashboard. The interface displays build statistics, asset analyze output, and task management features in a visually organized format.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.