Front knowledge

  • The node installation
  • npm(yarn,cnpm)
  • webpack(webpack-cli)

VUE CLI3 encountered a problem

Internet Explorer compatible processing, remove console

npm install @babel/polyfill -s
npm install transform-remove-console -s// Set babel.config.js to const plugins = []if (process.env.NODE_ENV === 'production') {// Remove console.log plugins.push('transform-remove-console')
}
module.exports = {
  presets: [
    ['@vue/app', {
      polyfills: [
        'es6.array.iterator'.'es6.promise'.'es7.promise.finally'.'es6.symbol'.'es6.array.find-index'.'es7.array.includes'.'es6.string.includes'.'es6.array.find'.'es6.object.assign'
      ]
    }]
  ],
  plugins
}


Copy the code

Fast construction of VUE project based on VUE-CLI3.0

This chapter describes how to build a project using VUE-CLI3.0 in detail. The project built with VUE-Cli3.0 in this chapter is based on the template file of Webpack, and the built project belongs to the single page (SPA) application. Therefore, the subsequent actions and instructions in this document are not applicable to building a multi-page application.

Compared with the previous, it has the following advantages:

  • Rich in features: Babel, Typescript, ESLint… Support is available out of the box
  • Easy to scale: Its plug-in system allows the community to build and share reusable solutions based on requirements
  • Eject free: Vue CLI is fully configurable, no longer using webPack configuration
  • CLI graphical interface: VUE UI Graphical interface to create, develop, and manage projects
  • Prototype now: Implement new ideas with a single Vue file
  • Look to the future: Easily produce native ES2015 code for modern browsers, or build your VUE Components as native Web Components

1. Vue-cli3.0 initialization

Install @ vue/cli

# npm install -g @vue/cli
OR
# yarn global add @vue/cli
Copy the code

You can check the version using vue –version or vue -v

  • VUE CLI3 package name byvue-clito@vue/cli. If you have installed an older version of VUE-CLI (1.x or 2.x), you go through it firstnpm uninstall vue-cli -goryarn global remove vue-cliUninstall it.
  • VUE CLI3 neednode8.9orhigher(recommended 8.11.0+)
  • VUE CLI3 uses the same VUE command as the older version, so VUE CLI2(VUe-CLI) is overwritten. If you still need to use older versions of vue Init, you will need to install a bridge tool globally:
npm install -g @vue/cli-init
Vue init webpack myVue
Copy the code

2. Create projects

You can use the Vue UI graphical interface to create and manage projects. This is not explained here. Please see cli.vuejs.org/ to create projects from the command line:

vue create vuedemo
Copy the code

You will be prompted to choose a preset. You can choose preset, which includes the basic Babel+ESLint setting, or preset can be selected by a preset feature.

This default setting is great for quickly prototyping a new project, while manual Settings provide more options that are more desirable for production-oriented projects, such as “Manual Settings”. The next key to move, to the space bar whether to select

  • Babel: Compile ES6 to ES5
  • TypeScript: A superset of javascript types
  • Progressive Web App (PWA) Support: Support for Progressive Web applications
  • Router:vue-router
  • Vuex: status management
  • CSS pre-processors: PRE-processors
  • Linter/Formatter: Development specification
  • Unit Testing: Unit Testing
  • E2E Testing: end-to-end Testing

If you later want to install the plugin in an already created project, you can use the vue add command:

D:\i\vuedemo> vue add vuex
Copy the code

If the preceding information is displayed, the installation is successful. Run the CD vuedemo and YARN Serve command.

3. Configuration file description

Vue-cli3.0 is dedicated to the standardization of the tool base in the VUE ecosystem. It ensures that the various build tools work smoothly based on smart defaults, so you can focus on writing your application and reduce the time spent configuring it. If you look at the following files, you can see that the build and config folders are missing compared to vue-cli2.0, so vue-cli3 provides an optional configuration file called vue.config.js. Please refer to 4 and 5(Packaging configuration) for details on file functions.

|-- dist                       # Post pack folder
|-- public                     # static folder
|   |-- favicon.ico				
|   |-- index.html					# Entry page
|-- src                        # source directory
|   |--assets						# Module resources
|   |--components					# vue common component
|   |--views 						
|   |--App.vue                                          # page entry file
|   |--main.js	                                        # import file, load the public component
|   |--router.js                                        # Route configuration
|   |--store.js	                                        # State management
|-- .env.pre-release          # Pre-release environment
|-- .env.production	      # Production environment
|-- .env.test		      # Test environment
|-- vue.config.js             # config file
|-- .eslintrc.js    		  	# ES - lint calibration
|-- .gitignore          		Git ignores the format of the uploaded file
|-- babel.config.js   			# Babel syntax compilation
|-- package.json       	     # Basic project information
|-- postcss.config.js   	 	# CSS preprocessor (autoprefixer enabled by default)
Copy the code

4. Vue.config. js configuration

Vue. Config. js is an optional configuration file that is automatically loaded by @vue/ CLI-service if it exists in the root directory of the project. You can also use the vue fields in package.json, but be careful to stick to the JSON format. This is handled by configuring vue.config.js.

const webpack = require('webpack')
module.exports = {
    // The base URL when deploying the application package
    publicPath: process.env.NODE_ENV === 'production' ? '/online/' : '/'.// Directory of the production environment build file generated when vue-cli-service build is run
    outputDir: 'dist'.// Place the generated static resources (js, CSS, img, fonts) in the directory (relative to outputDir)
    assetsDir: 'assets'.// eslint-loader checks whether the @vue/cli-plugin-eslint installation is valid while saving
    lintOnSave: true.// Whether to use the Vue build with the runtime compiler. After setting true, you can use template again
    runtimeCompiler: true.// Whether the production environment generates the sourceMap file see the end for details about sourceMap
    productionSourceMap: true.// Allows us to control the internal configuration of webpack more fine-grained, for example: we can successfully change the configuration rules rule to the urL-loader value under the image of the Module in Webpack and change its limit to 5M
    chainWebpack: config= > {
        config.module.rule("images")
        .use("url-loader")
        .tap(options= >
        merge(options, {
        limit: 5120
    }));
    },
    // Error reporting console.log can be turned off in a formal environment.
    configureWebpack: config= > { 
        if (process.env.NODE_ENV === 'production') {
            // Modify the configuration for the production environment...
        } else {
            // Modify the configuration for the development environment...}},// CSS related configurations
    css: {
        // Whether to use CSS ExtractTextPlugin: True in production environment, false in development environment
        extract: true.// Enable CSS source maps?
        sourceMap: false.// CSS default configuration item
        loaderOptions: {},
        // Enable CSS modules for all CSS/pre-processor files.
        modules: false
    },
    // webpack-dev-server configuration
    devServer: { // Set the proxy
        hot: true./ / thermal load
        host: '0.0.0.0'./ / IP address
        port: 8085./ / port
        https: false.//false Disables HTTPS. True enables HTTPS
        open: true.// Automatically open the browser
        proxy: {
            '/api': { / / local
            target: 'http://192.168.102.13:8080/'.// If you want to delegate WebSockets
            ws: true.changeOrigin: true
      },
      '/test': { / / test
        target: 'http://172.22.0.58:8082/'
      },
      '/pre-release': {  / / pre-release
        target: 'http://XXX.com/'
      },
      '/production': { / / formal
        target: 'http://XXX.com/'}}},pluginOptions: { // Third-party plug-in configuration
        // ...}}Copy the code

Extension:

What the Source Map does: Processing of packaged code is an information file that stores location information. That is, every position in the transformed code corresponds to the position before the transformation. With this, when something goes wrong, the debugger will display the original code instead of the converted code. This undoubtedly brings great convenience to developers.

5. Package the configuration

In the actual project development, we often experience project development phase, testing phase, online pre-release stage and final stage, each stage may be different to the requirement of the project code, so how we can function under the different stages to make our project present different effect, use different functions? This is where the concept of environment comes in.

Typically, a project will have the following four environments:

  • Development environment (development phase, local development version, usually with some debugging tools or additional accessibility)
  • Test environment (during the test phase, the pre-launch version, except for some bug fixes, will not be much different from the launch version)
  • Pre-release environment (in the upcoming launch stage, the pre-launch version, the possibility of online problems predicted, no different from the launch version)
  • Production environment (during the launch stage, the version officially released will be optimized and error reporting will be turned off)

As developers, we may need to write some different code for each environment and make sure it runs in the right environment, which requires proper environment configuration and management.

Create the.env.test file with the following contents

NODE_ENV='test'                    # Test environment
VUE_APP_TT='TT'
Copy the code

Create a.env.pre-release file with the following contents:

NODE_ENV='pre-release'              # Pre-release environment
Copy the code

Create. Env. production file with the following contents:

NODE_ENV='production'              # Formal environment
VUE_APP_T='la'
Q='1'
Copy the code
Package. The json configuration
"scripts": {
    "serve": "vue-cli-service serve "."build:pre": "vue-cli-service build --mode pre-release".# Pre-release environment
    "build:test": "vue-cli-service build --mode test".# Test environment
    "build:prod": "vue-cli-service build --mode production".# Formal environment
    "lint": "vue-cli-service lint"."test:unit": "vue-cli-service test:unit"
}
Copy the code

Note:

  • Used in vue. Config. Jsprocess.env.[name]Just make an interview
// vue.config.js console.log(process.env.NODE_ENV); // development (output in terminal)Copy the code
  • After you run the yarn serve command, the output is development. The default setting of the vue-cli-service serve command is development. You need to modify the serve script in package.json as follows:
"scripts": {
"serve": "vue-cli-service serve --mode test",}Env.[model]; / / if you do not find the corresponding configuration file, you will use the default environment development. Also, vue-cli-service build will use the default production environment.
Copy the code
Notes on environment variables
  • The environment name should be consistent with the environment file
  • Environment files are placed in the root directory
  • In addition tobaseUrlNODE_ENVUse other environment variablesVUE_APPAt the beginning

Deploy cross-domain processing of projects

After the project is packaged and goes online, the cross-domain processing configured in the development and debugging mode of the VUE project is invalid, and the cross-domain processing depends on the configuration to access the back-end service.

The first solution is to add CORS cross-domain resource sharing to the backend. Java and.NET code are different, but the main recognition is to set the Http “Origin” related properties.

The second method sets the HTTP server at the back end to filter all HTTP requests and increase cross-domain CORS resource sharing.

Front-end development can not be involved in these two ways, and needs to communicate with developers provided by back-end services and operation and maintenance of deployment services.

Githup address: github.com/Mr-jili/vue…

Please give your opinions, check the omissions and fill in the gaps, what deficiencies please give your opinions. Pooh, the document needs to be submitted to the leader