https://gitee.com/lz-126/vue3-cli4#top

vue3-cli4

Warehouse address = = = = >
Reference address

Project setup

yarn install

Compiles and hot-reloads for development

yarn serve

Compiles and minifies for production

yarn build

Run your unit tests

yarn test:unit

Lints and fixes files

yarn lint

Customize configuration

See Configuration Reference.

Frame description

See Configuration Reference

  about old version
Vue CLI package name changed from Vue CLI to @ vue/cli. If you have globally installed the old version of Vue CLI (1. X or 2.x), you need to uninstall it through npm uninstall vue-cli-g or yarn global remove Vue CLI.

  Node version requirements
Vue CLI requires Node Js89 or higher (811.0 + recommended). You can use nvm or nvm windows to manage multiple Node versions on the same computer.

  install (uninstall) the new version
npm install -g @vue/cli
npm uninstall -g @vue/cli

@vue/cli 4.5.15

Project construction

  vue create Project name

  Babel	A method that allows the browser to automatically identify backward compatible versions JavaScript Function of (optional)
  TypeScript	one kind.ts Suffix compatible js Syntax of (not selected)
  Progressive Web App(PWA)Support	Progressive network application (not selected)
  Router	vue Routing management component (optional)
  Vuex	vue Warehouse management component (optional)
  CSS Pre-processors	CSS Precompiled (optional)
  Linter/Formatter	Code inspection format check (optional)
  Unit Testing	Unit test tests code from the perspective of development (not selected)
  E2E Testing	e2e Test test code from the user's point of view (not selected)

catalogue

✅ Configure multiple environment variables

  through package Add – mode xxx to the scripts configuration item in JSON to select different environments

  only Vue_ The variables at the beginning of app will be webpack Defineplugin is statically embedded into the package on the client side, and the code can be processed through process env. VUE_APP_ BASE_ API access

  NODE_ENV and base_ URLs are two special variables that are always available in code

to configure

  create a new one in the project root directory env, .env.production, .env.de and other documents

  • .env

  serve default local development environment configuration

#testing environment
NODE_ENV = "development"

# Set the directory of packaged output
OUTPUT_DIR='dist'

#Service address
VUE_APP_BASE_URL = "./"
#Picture address
VUE_APP_IMGBASE_URL = "./"
  • .env.production

(default server)

# production environment 
NODE_ENV = "production"

# Set the directory of packaged output
OUTPUT_DIR='dist_pro'

#Service address
VUE_APP_BASE_URL = "https://XXXXXXXX.com/"
#Picture address
VUE_APP_IMGBASE_URL = "https://XXXXXXX.com/"

  • .env.test

   test default environment configuration (test server)

# testing environment
NODE_ENV = "test"

# Set the directory of packaged output
OUTPUT_DIR='dist_test'

#Service address
VUE_APP_BASE_URL = "https://XXXXXXXX.com/"
#Picture address
VUE_APP_IMGBASE_URL = "https://XXXXXXX.com/"

  modify package json

"scripts": {
  "serve:pro": "vue-cli-service serve --mode production",
  "serve:build": "vue-cli-service serve --mode production",

  "serve:test": "vue-cli-service serve --mode test",
  "serve:test-build": "vue-cli-service serve --mode test",
}
Using environment variables
<template>
  <div class="home">
    <!-- template Using environment variables in -->
     BASE_URL: {{ BASE_URL }}
  </div>
</template>

<script>
export default {
  name: "home",
  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_URL
    };
  },
  mounted() {
    // Using environment variables in js code
    console.log("BASE_URL: ", process.env.VUE_APP_BASE_URL);

  }
};
</script>

▲ back to the top

✅ Configure basic Vue config. js

module.exports = {
  // The default is' / ', which is the basic URL when deploying the application package
  publicPath: IS_PROD ? process.env.VUE_APP_BASE_URL : "./",
  // Directory of production environment build files
  outputDir: process.env.OUTPUT_DIR,
  // Static resource (js, css, img, fonts) directory relative to outputDir
  // assetsDir: "", 
  
  // Does the eslint loader check when saving
  lintOnSave: false,
  // Close eslint
  devServer: {
    overlay: {
      warnings: false,
      errors: false
    }
  },
}

▲ back to the top

  assume that the mock interface is https://www.easy-mock.com/mock/5bc75b55dc36971c160cad1b/sheets/1

module.exports = {
  devServer: {
    overlay: { // Let the browser overlay display both warnings and errors
      warnings: true,
      errors: true
    },
    // open: false, / / whether to open the browser
    // host: "localhost",
    // port: "8080", / / the agent is disconnected
    // https: false,
    // hotOnly: false, / / hot update
    proxy: {
      "/api": {
        target:
          "https://www.easy-mock.com/mock/5bc75b55dc36971c160cad1b/sheets ", / / target proxy interface address
        secure: false,
        changeOrigin: true, // Open the agent and create a virtual server locally
        // ws: true, / / whether to enable websockets
        pathRewrite: {
          "^/api": "/"
        }
      }
    }
  }
};

  visit

<script>
import axios from "axios";
export default {
  mounted() {
    axios.get("/api/1").then(res => {
      console.log('proxy:', res);
    });
  }
};
</script>

▲ back to the top

✅ SVG to font

npm i -D svgtofont

   add scripts directory to the root directory and create svg2font JS file:

const svgtofont = require("svgtofont");
const path = require("path");
const pkg = require("../package.json");

svgtofont({
  src: path.resolve(process.cwd(), "src/icons/svg"), // svg icon directory path
  dist: path.resolve(process.cwd(), "src/assets/fonts"), // Output to the specified directory
  fontName: "icon", // Set font name
  css: true, // Generate font file
  startNumber: 20000, // unicode start number
  svgicons2svgfont: {
    fontHeight: 1000,
    normalize: true
  },
  // website = null, no presentation html file
  website: {
    title: "icon",
    logo: "",
    version: pkg.version,
    meta: {
      description: "",
      keywords: ""
    },
    description: ``,
    links: [{
        title: "Font Class",
        url: "index.html"
      },
      {
        title: "Unicode",
        url: "unicode.html"
      }
    ],
    footerInfo: ``
  }
}).then(() => {
  console.log("done!");
});

  add package JSON scripts configuration:

"font": "node scripts/svg2font.js",

  execution:

npm run font

▲ back to the top

✅ Using SVG components

npm i -D svg-sprite-loader

  added SvgIcon component.

<template>
  <svg class="svg-icon"
       aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`
    }
  }
}
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

  create icons folder in src folder. Add svg folder (used to store svg files) and index. In icons folder JS file:

// require.context(directory,useSubdirectories,regExp)
// Directory: indicates the directory to retrieve
// useSubdirectories: indicates whether to retrieve subfolders
// regExp: the regular expression that matches the file, usually the file name
// For example, require context("@/views/components",false,/.vue$/)
const requireAll = requireContext => requireContext.keys().map(requireContext);
const req = require.context("./svg", false, /\.svg$/);
requireAll(req);

  create index in the components folder JS file, which is used to export global components;

// Register to global
import SvgIcon from './SvgIcon.vue';

/**
 *  
  install(Vue,option){
        assembly
        instructions
        Mix in
        Mount vue prototype
  }
*/ 
const pubcom = {
  install(vue) {
    vue.component('SvgIcon', SvgIcon)
  }
}
  
export default pubcom


  in main JS import @ / components / index js , @/icons

// Global components
import pubcom from "@/components/index.js"
import "@/icons";

import {
  createApp
} from "vue";
import App from "./App.vue";

createApp(App)
  .use(router)
  .use(pubcom)
  .mount("#app");

  modify Vue config. js

const path = require("path");
const resolve = dir => path.join(__dirname, dir);

module.exports = {
  chainWebpack: config => {
   // svg component
    const svgRule = config.module.rule("svg");
    svgRule.uses.clear();
    svgRule.exclude.add(/modules/);
    svgRule
      .test(/\.svg$/)
      // .include.add(resolve('@/icons/svg') / / add the file path we want to process
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      });

    const imagesRule = config.module.rule("images");
    imagesRule.exclude.add(resolve("src/icons"));
    config.module.rule("images").test(/\.(png|jpe?g|gif|svg)(\?.*)?$/);

    return config;
  }
};

  using SVG components

<template>
 <div>
    <svg-icon icon-class="email"></svg-icon> mailbox
  </div>
</template>

▲ back to the top

✅ Provide sass with global styles and global variables

   you can use in main js createApp(App,{KaTeX parse error: Expected 'EOF', got '}' at position 44:... APP_IMGBASE_URL} ̲), Then use imgbase in js_ URL access.

  in css, you can use the injected sass variable to access the configuration information in the environment variable

const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);

module.exports = {

    // pages
  css: {
    // Extract the CSS in the component into a separate CSS file (only in the production environment)
    // It can also be an option object passed to 'extract text webpack plugin'
    extract: false, //IS_PROD
    // Open CSS source map?
    sourceMap: false,
    // Pass custom options to the loader of the preprocessor. For example, pass it to
    // When using Css loader, ` {Css: {...}} '.
    loaderOptions: {
      // The options here will be passed to CSS loader
      scss: {
        // Pass in the shared global variable to the global sass style, and $src can configure the picture cdn prefix
        // Details: https://cli.vuejs.org/guide/css.html#passing-options-to-pre-processor-loaders
        prependData: `
          @import "@scss/base.scss";
          @import "@scss/variables.scss";
          @import "@scss/mixins.scss";
          $src: "${process.env.VUE_APP_IMGBASE_URL}";
          `
      }
    }
  }
};

Reference in scss

.home {
  background: url($src+"/images/500.png");
}

▲ back to the top

✅ Add IE compatibility

  in main JS

import 'core-js/stable'; 
import 'regenerator-runtime/runtime';

Configure Babel config. js

const plugins = [];

module.exports = {
  presets: [["@vue/app", { useBuiltIns: "entry" }]],
  plugins: plugins
};

▲ back to the top

Keywords: Javascript Vue-cli Vue.js

Added by jsims on Wed, 23 Feb 2022 08:44:00 +0200