🤞 Setup project configuration 🤞

Here are some basic configurations of my project, you can refer to them if you need them!

Note:

1) Global properties start with VUE_APP

  • Note: VUE_APP is added to the global variable name after vuE-cli.3.0
  • For example: VUE_APP_API

2) During project configuration, an error will be reported if the import and export of ES5 and ES6 are confused:

  • TypeError: Cannot assign to read only property ‘exports’ of object ‘Uncaught TypeError: Cannot assign to read only property ‘exports’ of object’
  • Error: Mixing import and module.exports is not allowed in Webpack 2. Using the same file will cause an error
  • Module. exports = HTTP: export default HTTP

I. Project construction

1) User-defined construction project steps:

  vue create my-project  
    // Use the default configuration
    // Manually select features is a custom configuration

  Manually select features 
  // Up and down arrow to select, select the desired file, press the space bar to select (* in parentheses means selected)
  Use history mode for router?
  // If you want to use the route history router, it is recommended to select N, otherwise the server needs to be configured
  Pick a CSS pre-processor 
  // The CSS preprocessor is Sass/SCSS(with Dart-sass). Node-sass is automatically compiled in real time, and Dart-Sass needs to be saved before it takes effect
  Pick a linter/formatter config
  // Select ESLint code verification rules to provide a plug-in for javascript code detection. ESLint + Prettier is commonly used
  Pick additional lint features
  // Then select when to validate code, Lint on save is checked, Lint and fix on commit is checked, first recommended
  Where do you prefer placing config for Babel,PostCSS,ESLint,etc?
  // In dedicated config files, In package.json, In package.json
  Save this as a preset forfuture projects? (y/N)// Whether to save the configuration, N is not recorded, if you select Y, you need to enter the name to save

Copy the code

2) Project launch:

  • Command line: NPM run serve (NPM run dev after later configuration)
  • Note: the project sometimes encounters a sass error at runtime: the binding.node file cannot be found in the sass file. Note

– Error when running project:

  • Missing binding E:\my-project\node_modules\node-sass\vendor\win32-x64-83\binding.node Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 14.x

Error cause:

  • The binding. Node file could not be found under node_modules\node-sass\vendor\win32-x64-83\;

Solutions:

  • Method 1: Recompile node-sass: NPM rebuild node-sass
  • Method 2: from github.com/sass/node-s… Download the binding.node file of the corresponding version and place it under Node-sass \vendor.
  • For example, if you have downloaded the win32-x64-51_binding.node file, rename it to binding.node and save it to node-sass\vendor\win32-x64-51.

2. Related configuration

1). Environment variable configuration: (note: VUE_APP should be added to global variable name after VUE-cli.3.0)

1. Create a. Env file under the root directory (I use the following three types of files more often) :

.env.delelopment => Development environment

  # just a flag
  ENV = 'development'

  # base api
  VUE_APP_BASE_API = 'http://XXX'
Copy the code

.env.production => Production environment

  # just a flag
  ENV = 'production'

  # base api
  VUE_APP_BASE_API = 'http://XXX'
Copy the code

Env.testing => Test environment

  NODE_ENV = production

  # just a flag
  ENV = 'testing'

  # base api
  VUE_APP_BASE_API = 'http://XXX'
Copy the code

2. Perform related configurations in the package.json file:

  "scripts": {
      "dev": "vue-cli-service serve"."build:prod": "vue-cli-service build"."build:test": "vue-cli-service build --mode testing"."dev:serve": "vue-cli-service serve --mode development --inline"."dev:build": "vue-cli-service build --mode production"."dev:test": "vue-cli-service build --mode test"."lint": "vue-cli-service lint"
  }
Copy the code

3. Run/pack:

  npm run dev  // Project running
  npm run build:test  / / test package
  npm run build:prod  / / production package

Copy the code

2). The vue. Config. Js:

Create the vue.config.js file in the root directory and perform related configurations:

  module.exports={
      publicPath:process.env.NODE_ENV==='production'?'/':'/'
  }
Copy the code

Note the following points:

  1. Vue -cli 3.3 If “baseUrl” is configured after 3.3, an error will be reported: “BaseUrl is not allowed” Because vue-CLI version 3.3 disables baseUrl and uses publicPath instead.

  2. PublicPath accepts string values. The default value is ‘/’ (/ is the root directory). PublicPath sets the basic URL of the deployment application package, not the location where the packaged files of the project are stored. PublicPath can also be set to ” or ‘./’, which can be deployed arbitrarily after being set to a relative path.

3). Encapsulate HTTP requests:

Module. Exports/module. Exports/module. Exports/module.

0.1) API => request.js

  /** * encapsulates HTTP request methods */
  const { log } = console
  const axios = require('axios');
  import Vue from 'vue';
  import { Toast } from 'vant';
  Vue.use(Toast);

  const http = (params) = > {
    return new Promise((resolve, reject) = > {
      let adminToken = localStorage.getItem('adminToken'); // Get the token value in the cache
      let token = { 'Admin-Token': adminToken || ' ' }
      let contentType = params.header || ' ' (default: {" content-type ": "application/json"})

      // Request interception
      axios.interceptors.request.use(
        config= > {
          if (adminToken) {
            config.headers = Object.assign({}, token, contentType)
          }
          return config
        },
        error= > {
          Toast({
            message: error.message,
            duration: 1000
          });
          reject(error)
        }
      )

      axios({
        baseURL: process.env.VUE_APP_BASE_API + params.url, // url = base url + request url
        method: params.method || 'POST'.// The default value is POST
        headers: Object.assign({}, token, contentType),
        timeout: 30000.// request timeout
        data: params.data, // Post request parameters
        params: params.param // get request parameters

      }).then(res= > {
        // The interface returns data normally
        if (res.status == 200) {
          if (res.data.code == '9001') {  // Code value agreed with the background. 9001 is the value when the token is invalid
            Toast({
              message: res.data.message,
              duration: 1000
            });
            reject(res.data.message)
          } else {
            resolve(res.data)
          }
        } else {
          //2. If the operation fails, the data is returned and the response message is displayed in toast mode. If the backend does not format the exception message that the operation failed, the unified exception message can be defined
          let errMsg = res.data.message
          Toast({
            message: errMsg,
            duration: 1000
          });
        }
      }).catch(err= > {
        Toast({
          message: err.message,
          duration: 1000
        });
        reject(err)
      })
    })
  }

  // module.exports = http
  export default http
Copy the code

0.2) API => index.js

  // const http = require("./request.js");
  import http from './request'

  // The interface is configured for different servers
  const panel = '/query1';
  const common = '/query2';

  var url = {
    list: `${common}/data/list`.submit: `${panel}/data/submit`,}const API = {
    list(param) {
      return http({
        url: url.list,
        method: 'GET'./ / get request
        param: param
      })
    },
    submit(data) {
      return http({
        url: url.submit,  // Post requests do not need to be written.
        data: data
      })
    }

  }
  // module.exports = API
  export default API
Copy the code

0.3) in the main. Js

  import API from "./api/index.js" / / interface
  Vue.prototype.VUE_APP_API = API; / / interface

  // Add a dynamic title configuration
  // Set the dynamic title
  router.beforeEach((to, from, next) = > {
    /* Route change page title */
    if (to.meta.title) {
      document.title = to.meta.title
    } else {
      document.title = 'title'
    }
    next()
  });
Copy the code

0.4) Page use:

  let data = {} // Interface parameters
  this.VUE_APP_API.adminConfirm(data)
      .then(res= >{})
      .catch(err= >{})
Copy the code

4). Route configuration:

  import Vue from 'vue'
  import Router from 'vue-router'
  import VueRouter from 'vue-router'

  Vue.use(Router)

  const routes = [{
      path: '/index'.name: 'home'.component: resolve= > require(['@/views/home/index'], resolve)
    }
  ]

  const router = new VueRouter({
    routes
  })

  export default router;
Copy the code