current position:Home>Vue + typescript + elementui actual combat (IV) global settings

Vue + typescript + elementui actual combat (IV) global settings

2022-04-29 20:34:43Yushia

1、 Multi environment configuration

Multiple environment variables are used in project development · pack · Concepts generated during production , The so-called multi environment variable means that a project adapts to multiple environments .

  • development environment : Generally, it is the environment used for local development , Changes are frequent
  • Test environment : A more stable version , Generally used for deployment testing
  • Production environment : The version published online

1.1 Configure startup commands

Configuring different environment variables can avoid manually modifying the project configuration when switching between different environments , request url etc.

stay package.json This is set in the file :

"scripts": {
    "serve": "vue-cli-service serve",   // development environment 
    "serve:test": "vue-cli-service serve --mode test", // Test environment 
    "build:test": "vue-cli-service build --mode test",
    "build:production": "vue-cli-service build --mode production", // Production environment 
 Copy code 

1.2 Created in the root directory .env file

Be careful :.env The file is the environment configuration , Random naming is not allowed


#  development environment 

#  development environment , Address of the interface 
 Copy code 


#  Production environment 

#  Production environment , Address of the interface 
 Copy code 


#  Test environment 
NODE_ENV =test

#  Test environment , Address of the interface 
 Copy code 

The main points of

  • .env The default attributes in the file are NODE_ENV and BASE_URL
  • The added property name must begin with VUE_APP_ start , Such as :VUE_APP_XXX
  • Can pass process.env Access the current environment configuration properties anywhere

1.3 get attribute

// process.env  According to the current environment , Load the variables in the corresponding environment variable file 
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
 Copy code 

2、SCSS To configure

2.1 Style initialization

effect : Because of the compatibility of browsers , Different browsers have different default values for some tags , If it's not right CSS Initialization often leads to page display differences between browsers .


yarn add normalize.css
 Copy code 

Use main.js Import normalize.css

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

+ import 'normalize.css' // Direct import 

 Copy code 

Direct download is recommended normalize.css, And then in main.js introduce

2.2 Use Element UI

Add dependency

yarn add element-ui
 Copy code 

Change... In the project SCSS Variable

Element Of theme-chalk Use SCSS To write , If your project also uses SCSS, Then it can be changed directly in the project Element Style variables for . Create a new style file , for example element-variables.scss, Write the following :

/*  Change the theme color variable  */
$--color-primary: teal;

/*  change  icon  Font path variable , It's necessary  */
$--font-path: '~element-ui/lib/theme-chalk/fonts';

@import "~element-ui/packages/theme-chalk/src/index";
 Copy code 

after , In the project's entry file , Directly import the above style files ( There is no need to introduce Element compiled CSS file ):

// main.ts
import Vue from 'vue'
import Element from 'element-ui'
import './element-variables.scss'

 Copy code 

Be careful The following error is reported if

 Insert picture description here terms of settlement sass The version is revised to 1.32.13, Execute the following command

yarn add [email protected]
 Copy code 

2.3 Variable configuration

stay src/assets/scss Create a new variable configuration file :mixin.scss

//  overall situation scss Variable 
$theme-color: #317FEA;
$activeColor: #147af7;

//  Exposure to js Variable 
:export {
  themeColor: $theme-color;
 Copy code 

vue.config.js File configuration ( Restart project )

module.exports = {
  outputDir: 'dist',
  publicPath: '/',
  //  To configure scss File global variables 
  css: {
    loaderOptions: {
      //  No semicolon will report an error 
      sass: {
        // data: '@import "@/assets/css/vars.scss";' // Old edition sass-loader How to write it (8.0 following )
        prependData: `@import "@/assets/scss/minix.scss";` // new edition scss-loader(8.0 And above )
 Copy code 

Directly used in other components

&:hover {
   color: #fff;
   background: $activeColor;
 Copy code 

3、vue.config.js To configure

Related configuration instructions

//  there webpack The configuration will be shared with the public webpack.config.js A merger 
module.exports = {
  //  perform  npm run build  Unified configuration file path ( Local access dist/index.html Need to be './')
  // NODE_ENV:Node.js  System environment variables exposed to executing scripts . It is usually used to determine whether it is in a development environment or a production environment 
  // publicPath: '/',
  publicPath: process.env.NODE_ENV === 'production' ? '' : '/',
  outputDir: 'dist', //  Output file directory 
  // assetsDir: 'static', //  Place static resources 
  // indexPath: 'index.html', //  Can not be set. Generally, it defaults to 
  // filenameHashing:true, //  File naming 
  lintOnSave: false, // Set whether to enable... Every time you save code in the development environment  eslint verification 
  // runtimeCompiler: false, //  Whether to use a full build with an in browser compiler 
  configureWebpack: { //  Alias configuration 
    resolve: {
      alias: {
        //'src': '@',  Default configured 
        'assets': '@/assets',
        'common': '@/common',
        'components': '@/components',
        'api': '@/api',
        'views': '@/views',
        'plugins': '@/plugins',
        'utils': '@/utils',
    //  Add... Before use ~
  productionSourceMap: false, // If you don't need a production environment  source map, You can set it to  false  To speed up production environment building 
  css: { // css Related configuration 
    //  Whether to change the  CSS  Extract to a separate  CSS  In file , In the production environment it's  true, The development environment is  false
    extract: process.env.NODE_ENV === "production",
    //  Is it  CSS  Turn on  source map. Set to  true  Later it may affect the performance of the build .
    sourceMap: false,
    //  Enable  CSS modules for all css / pre-processor files.( Preloading )
    requireModuleExtension: true,
    loaderOptions: {
      scss: {
        // data: '@import "@/assets/css/vars.scss";' // Old edition sass-loader How to write it (8.0 following )
        prependData: `@import "@/assets/scss/minix.scss";` // new edition scss-loader(8.0 And above )
  devServer: {
    port: 2021, //  Set the port number 
    host: '', // ip
    disableHostCheck: true, // Whether or not to turn off for  DNS  Rebinding  HTTP  Requested  HOST  Check 
    hotOnly: false, //  Hot update 
    https: false, // https:{type:Boolean} Configure prefix 
    open: false, // Configure auto launch browser 
    proxy: null,  // Setting agent 
    // proxy: { // The purpose is to solve cross domain problems , If the test environment does not need to cross domain , This configuration is not required 
    // '/api': { //  Intercept with  /api  At the beginning url Interface 
    // target: '', // Target interface domain name 
    // changeOrigin: true, // Cross domain or not 
    // ws: true, // If you want an agent  websockets, Configure this parameter 
    // secure: false, //  If it is https Interface , This parameter needs to be configured 
    // //  Identification replacement 
    // //  The original request address is  /api/getData  take '/api' Replace '' when ,
    // //  The request address after proxy is :
    // //  If replaced by '/other', Then the request address after proxy is 
    // pathRewrite: { //  Identification replacement 
    // '^/api': '/' // Rewrite interface   Background interface points are not uniform   So point to all /
    // '^/api': '/api/mock'
    // }
    // }
    // }
  //  Added to this plug-in service worker Enable only in the production environment ( for example , Only if you run npm run build or yarn build when ).
  //  Enabling... In development mode is not recommended service worker, Because it leads to the use of previously cached assets without including the latest local changes .
  pwa: {
    // serviceWorker:false,
    //  Allows you to start from an existing service worker File start , And create a copy of the file , And will “ Pre cache list ” Inject it .
    // workboxPluginMode:'InjectManifest',
    // workboxOptions: {
    // //swSrc: './app/sw.js', /* Empty file. */
    // },
    iconPaths: {
      favicon32: "favicon.ico",
      favicon16: "favicon.ico",
      appleTouchIcon: "favicon.ico",
      maskIcon: "favicon.ico",
      msTileImage: "favicon.ico"
 Copy code 

4、.eslintrc.js Frequently asked questions and configuration

4.1 common problem

Report a mistake :

ESLint: Missing return type on function.(@typescript-eslint/explicit-module-boundary-types)

resolvent :

stay .eslintrc.js Add rules to the file to disable it

 "rules": {
     "@typescript-eslint/explicit-module-boundary-types": "off"  
 Copy code 

Error reporting II :

ESLint: Type string trivially inferred from a string literal, remove type annotation.(@typescript-eslint/no-inferrable-types)

Error reason : TypeScript Code similarity :

const web: string = "Hello World";
 Copy code 

Simply infer the string type from the string text , Delete type comment .eslint @ typescript-eslint / no-inferrable-types He thought he had inferred that it was a string type , No need to write

resolvent : stay .eslintrc.js Add rules to the file to disable it

rules: {
    "@typescript-eslint/no-inferrable-types": "off" //  Close type inference 
 Copy code 

Error reporting 3 :

ESLint: Require statement not part of import statement. [email protected]/no-var-requires

resolvent :

 "rules": {
    '@typescript-eslint/no-var-requires': 'off'
 Copy code 

Error reporting 4 :

warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any

Solution :

close any Type of warning .

 "rules": {
    '@typescript-eslint/no-explicit-any': 'off'
 Copy code 

Report five mistakes :

ESLint: Forbidden non-null assertion.(@typescript-eslint/no-non-null-assertion)

Solution :

 "rules": {
    @typescript-eslint/no-non-null-assertion': 'off' },  Copy code 

Report six mistakes :

SLint: ‘xxx’ is not defined.(no-undef) // Description the global variable is undefined

Solution :

 "rules": {
    "xxx": true//xxx  For your global variables 

 Copy code 

The configuration of my project is as follows :

module.exports = {
  root: true,
  env: {
    node: true
  extends: [
  parserOptions: {
    ecmaVersion: 2020
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'space-before-function-paren': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/no-var-requires': 'off'
 Copy code 

5、tsconfig.json explain

Generate a... Under the root directory of the project tsconfig.json file , Here's a copy tsconfig.json Explanation :

  "compilerOptions": {
    /*  The basic options  */
    "target": "es6",                       //  Appoint  ECMAScript  Target version : 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
    "module": "commonjs",                  //  Specify module to use : 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "lib": [],                             //  Specify the library files to include in the compilation 
    "allowJs": true,                       //  Permitted compilation  javascript  file 
    "checkJs": true,                       //  The report  javascript  Error in file 
    "jsx": "preserve",                     //  Appoint  jsx  Code generation : 'preserve', 'react-native', or 'react'
    "declaration": true,                   //  Generate corresponding  '.d.ts'  file 
    "sourceMap": true,                     //  Generate corresponding  '.map'  file 
    "outFile": "./",                       //  Merge output files into one file 
    "outDir": "./",                        //  Specify output directory 
    "rootDir": "./",                       //  Used to control the output directory structure  --outDir.
    "removeComments": true,                //  Delete all comments after compilation 
    "noEmit": true,                        //  Do not generate output file 
    "importHelpers": true,                 //  from  tslib  Import helper functions 
    "isolatedModules": true,               //  Make each file a separate module  ( And  'ts.transpileModule'  similar ).
    /*  Strict type checking options  */
    "strict": true,                        //  Enable all strict type checking options 
    "noImplicitAny": true,                 //  Implicit in expressions and declarations  any Wrong type 
    "strictNullChecks": true,              //  Enable strict  null  Check 
    "noImplicitThis": true,                //  When  this  Expression value is  any  When it comes to type , Generate an error 
    "alwaysStrict": true,                  //  Check each module in strict mode , And add it to every document  'use strict'
    /*  Additional checks  */
    "noUnusedLocals": true,                //  When there are unused variables , Throw an error 
    "noUnusedParameters": true,            //  When there are unused parameters , Throw an error 
    "noImplicitReturns": true,             //  When not all code in a function has a return value , Throw an error 
    "noFallthroughCasesInSwitch": true,    //  The report  switch  Of the statement  fallthrough  error .( namely , Don't allow  switch  Of  case  Sentence through )
    /*  Module resolution options  */
    "moduleResolution": "node",            //  Select module resolution strategy : 'node' (Node.js) or 'classic' (TypeScript pre-1.6)
    "baseUrl": "./",                       //  Base directory for resolving non relative module names 
    "paths": {},                           //  Module name to based on  baseUrl  List of path mappings for 
    "rootDirs": [],                        //  Root folder list , Its combined content represents the structural content of the project at runtime 
    "typeRoots": [],                       //  List of files containing type declarations 
    "types": [],                           //  List of type declaration filenames to include 
    "allowSyntheticDefaultImports": true,  //  Allow default import from modules with no default export set .
    /* Source Map Options */
    "sourceRoot": "./",                    //  Specifies that the debugger should find  TypeScript  Location of files instead of source files 
    "mapRoot": "./",                       //  Specifies where the debugger should find the map file instead of the build file 
    "inlineSourceMap": true,               //  Generate single  soucemaps  file , Rather than  sourcemaps  Generate different files 
    "inlineSources": true,                 //  Linking code to  sourcemaps  Build to a file , Requirements are set at the same time  --inlineSourceMap  or  --sourceMap  attribute 
    /*  The other options  */
    "experimentalDecorators": true,        //  Enable decorator 
    "emitDecoratorMetadata": true          //  Provide metadata support for decorators 
 Copy code 

copyright notice
author[Yushia],Please bring the original link to reprint, thank you.

Random recommended