Author: gauseen

About 0.Vuejs

  • Brief introduction:Vue(pronunciation/ vju ː /, similar to theview) is a set of progressive frameworks for building user interfaces that are easy to use, flexible and efficient.
  • The ecological system
project introduce
awesome-vue Vue.jsGreat tool set
vue-router Vue.jsOfficial routing manager
vuex Vue.jsApplication status management tools
vue-cli Quick one-click buildVue.jsApplication development environment
vue-loader webpackloader, parsing.vueFiles, which allow you to write in a format called single-file components (SFCs)Vuecomponent
vue-server-renderer Server-side rendering (ssr)
vue-rx integrationRxJS(Tools for handling events)
vue-devtools Vue.jsDevelop the debug tool browser plug-in

1. Develop specifications

  • JavaScript Standard
  • Vue coding style specification
  • Project catalog specification

2. Create projects

Install the Vue CLI
yarn global add @vue/cli

Initialize the project
vue create hello-world-3x

cd hello-world-3x

# Run the project locally
yarn serve
Copy the code

Static resources

Static resources can be processed in two ways:

  • inJavaScriptTo be imported or intemplate/CSSIs referenced by a relative path. This kind of reference will bewebpackTo deal with.
  • Placed in thepublicDirectory or through an absolute path. Such resources will be copied directly without passing throughwebpackProcessing.
  • URLTransformation rules
    • ifURLIs an absolute path (e.g. /images/foo.png) that will be left unchanged.
    • ifURL.Initially, it is interpreted as a relative module request and resolved based on the directory structure in your file system.
    • ifURL~At the beginning, anything after that is parsed as a module request. This means you can even reference resources in Node modules:
    • ifURL@Initially, it will also be resolved as a module request. It’s useful becauseVue CLIA point is set by default<projectRoot>/srcThe alias@

4. publicfolder

  • Any place onpublicThe static resources of the folder are copied tooutputDirIn the directory of the corresponding value (default'dist').
  • If an absolute path is used, it will not bewebpackProcessing (Only one copy of the resource exists);
  • If you refer to it in a relative path, it will bewebpackProcess, repackage the image to<outputDir>/<assetsDir>/img/Directory, and add to the picturehashValue for better control of the cache.There will be two copies of the resource(And a copy of the first one)
  • So the referencepublicYou are advised to use an absolute path for folder static resourcespublicPathThe prefix
<img :src="`${publicPath}logo.png`">
Copy the code
data () {
  return {
    publicPath: process.env.BASE_URL,
  }
},
Copy the code

5. vue.config.js

  • PublicPath (same as baseUrl, deprecated by Vue CLI 3.3)

    What it does: Set all static resource path prefixes processed by Webpack (excluding resources referenced with absolute paths)

    Default: ‘/’

    By default, the Vue CLI assumes that your application is deployed on the root path of a domain name, such as https://domain.com. PublicPath does not need to be set deliberately. If the application is deployed on a subpath, you need to specify the subpath with this option, such as https://domain.com/my-app/, then publicPath is /my-app/.

  • Webpack configuration Vue CLI internal configuration is maintained through webpack-chain, making the configuration of Webpack easier to modify in the later period.

    For CSS-related loaders, we recommend using CSs. loaderOptions instead of directly chained loaders. This is because there are multiple rules for each CSS file type, and CSS.loaderOptions ensures that you affect all rules in one place

// vue.config.js

// CSS Loader configuration
css: {
  loaderOptions: {
    stylus: {},}},// Webpack other configurations
chainWebpack: config= > {
    // Configure the alias
    config.resolve.alias
      .set('rootDir', path.join(__dirname))
    config.module
    // Add a named rule for later modification
      .rule('compile')
        .test(/\.js$/)
        .include
          .add('src')
          .end()
        // You can even create a named loader for later modification
        .use('babel')
        .loader('babel-loader')
        .options({
          presets: [['@babel/preset-env', { modules: false}}]])// Modify the named loader
    config.module
      .rule('compile')
        .use('babel')
          .tap(options= > newOptions)
Copy the code

6. Check the WebPack configuration

vue inspect > output.js Output webPack configuration information in development mode
vue inspect --mode production > output.js Output webPack configuration information in production mode
Copy the code

7. Support multi-environment mode packaging

Scenario: There are various online environments including development, test, Preview and production. Each environment uses different variable values. How to solve the problem with the program?

Vue-cli 3.x Supports multiple environment mode variables

.env                Load in all environments
.env.local          # is loaded in all environments, but ignored by Git
.env.[mode]         Is loaded only in the specified mode
.env.[mode].local   # is only loaded in the specified mode, but is ignored by Git
Copy the code

Environment variable priority: Specifies the name of the environment variable. The more the environment variable, the higher the priority. Env. Production >.env

By default, vue-CLI 3.x supports only three modes:

  • Development mode Used for vue-CLI-service serve
  • Production mode is used for vue-cli-service build
  • The test mode is used for vue-cli-service test:unit and vue-cli-service test: e2E

So how do you add new modes?

You can specify a specific environment mode for the command line vue-cli-service by passing the –mode option parameter. For example: new preview mode

  • The project root directory is added.env.previewFile, as each mode will by defaultNODE_ENVIs set to the name of the schema, so addNODE_ENV=productionVariable (previewMode also needs to be packaged to upload server).
  • package.json scriptsFile add script command
    "build:preview": "vue-cli-service build --mode preview"
    Copy the code
  • runyarn build:previewPackage and compile

Mock data API management tool

Split development at the front and back ends has become common, and mock data has become an inevitable problem for the sake of parallel development at the front and back ends. There are many ways to mock data for the front end:

  • Mock.js simulates a data generator

    • The front-end needs to write manuallymockData code, more trouble
    • Have one for each projectmockCode, reuse rate bottom
    • There is noGUIVisual interface, not convenient backend development view interface, fields, etcapiinformation
  • Easy-mock is a persistent service that visualizes and quickly generates mock data

    • Support visual interface
    • Support for collaborative editing
    • supportswaggerCan be based onswaggerQuickly create project interfaces
    • supportMock.jsgrammar
    • Support for interface previews, etc
    • Free and open source, easy to deploy privately
  • RAP and RAP2 Ali mom produced, open source interface management tool RAP first generation and second generation

    • Support visual interface
    • Support for collaborative editing
    • supportMock.jsgrammar
    • Does not supportswaggerData import, but supportedJSONImport and export format data
    • Free and open source, but private deployment is relatively cumbersome
  • YApi is a visual interface management platform that can be deployed locally, connecting back and forth to QA

    • Support visual interface
    • Support for collaborative editing
    • Support for automated testing, yesResponseAssertion: star:
    • Based on theJson5MockjsDefine the structure and documentation of the data returned by the interface
    • supportSwagger, Postman, JSON, HARData import
    • Free and open source, easy to deploy privately

9. Vue project uses API interface to manage platform

// vue.config.js

// Base address
const baseApi = '/api'
// YApi project ID
const mockProjectId = '66666'

module.exports = {
  / / agent
  devServer: {
    proxy: {
      // Development environment agent
      [`${baseApi}/ (? ! mock)`] : {target: process.env.VUE_APP_DOMAIN || 'http://test.domain.com'.// Test the environment
        changeOrigin: true,},// Mock data proxy
      [`${baseApi}/mock`] : {target: 'http://yapi.demo.qunar.com'.changeOrigin: true.pathRewrite: {[`${baseApi}/mock`] :`/mock/${mockProjectId}${baseApi}`,},},},},}Copy the code

10. Preview the package code locally

Http-server is a Node-based, zero-configuration command line HTTP server.

# installation
yarn add -D http-server

# package.json scripts
"scripts": {
  "preview": "http-server ./ -P",},# Package output
yarn build

Dist / ===> my-app/ dist/ ===>
mv -rf dist/ my-app/

# Local preview (http://ip:port optional, for proxy service)
yarn preview <http://ip:port>

Open the browser to access
Copy the code

11. Online deployment

This section focuses on front – and back-end separated online deployment

Currently, two routing modes are used, hash and history

  • Hash pattern

    • The style is ugly and does not conform to people’s “aesthetics”.
    • Browser address barURL#(such as:http://localhost:3000/#/a)
    • #The following content is not passed to the server
    • Change the browser address barURL #And then the value,Don’t causeWeb page reloading
  • The history mode

    • HTML5New features, elegant style
    • Browser address not available#(such as:http://localhost:3000/a)
    • There is no#All,domainEverything that follows is passed to the server
    • Change the browser address barURL willReload the page, request the server again, and request thehistoryInsert a record into the stack

See the difference here

  • webThe server

The front-end page needs to run in the Web server, mainly including Nginx, Apache, IIS and so on, mainly processing some static resources. Our company uses Nginx. Here are some configurations of Nginx when deploying front-end applications:

  • hashPattern configuration
location^ ~ /pos2/
{
  root /data/www/webproject;
  index  index.html index.htm;
}
Copy the code
  • historyPattern configuration
location^ ~ /crmwap/
{
  root /data/www/webproject;
  try_files $uri $uri/ /crmwap/index.html =404;

  $document_root = root = /data/ WWW /webproject

  Try_files $uri $uri/ /crmwap/index.html =404; Fall back as follows:
  # $document_root$uri --> $document_root$uri/ --> $document_root/crmwap/index.html --> nginx 404

  Try_files $uri $uri/ /crmwap/index.html; Fall back as follows:
  # $document_root$uri --> $document_root$uri/ --> http://domain.com/crmwap/index.html
}
Copy the code

Nginx common commands

# start
start nginx

# to restart
nginx -s reload

# close
nginx -s stop
Copy the code

Note: The last location of try_files (fall back) is special (root only) and will issue an internal “sub-request” instead of looking up the file directly on the file system. The front-end pages are published iteratively without changing the Nginx configuration file, without the need to restart the Nginx service.

12. Automated build tools

  • Jenkins

Welcome to pay attention to the public number: learning front end