Table of Contents
Steps
Development
1. Initialize the project
This article mainly does three things:
Home Web Front-end JS Tutorial Vue front-end architecture learning (1)

Vue front-end architecture learning (1)

Feb 02, 2018 pm 01:53 PM
front end study Architecture

In this article, we mainly share with you Vue front-end architecture learning (1). This is a sharing of Vue front-end architecture from scratch. I hope it can help everyone.

Think about it, I have already done a lot of architectural projects, some based on vue, based on react, based on thinkPHP, based on laravel. If you do it too much, you will have various ideas about the existing architecture, some good and some bad. In short, it is still not comfortable to use. Although vue-cli can be built and used quickly, especially vue-cli v3.0, webpack is sealed into the @vue/cli SDK, making it cleaner and more concise to use.

Okay, now that the introduction is complete, I will start from scratch and build a front-end architecture step by step with completely separated front and back ends.

Steps

Since there is a lot to introduce, it is all written in one article, which is too long.

So, I will divide it into:

  1. Create the webpack configuration file in the development environment

  2. Configure eslint, babel, postcss

  3. Create project files and directory structure

  4. Implement local data interface simulation through koa

  5. Create the webpack configuration file in the release environment

  6. Create the webpack configuration file in the test environment and test cases (TODO)

  7. Automatic initialization and build Project (TODO)

These seven articles will be introduced separately.

Development

1. Initialize the project

  1. Create the project folder

We will call itvue-construct

  1. ##Initialize git

##git init

    Initialize npm
npm init

    Create project file
  1. In order to make webpack run, instead of just talking about the configuration without running it, it would be a bit empty, so we first create some project files and directories.
Before this, we first install two packages: vue, vue-router,

npm i -S vue vue-router
. We put all project code related files in a folder named app
. I'll create them all first, and then introduce them one by one. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">├── app │   ├── app.vue │   ├── common │   │   ├── img │   │   ├── js │   │   └── scss │   ├── index.html │   ├── index.js │   ├── router │   │   └── index.js │   └── views │       └── home │           └── index.vue ├── .gitignore ├── package-lock.json ├── package.json └── webpack.config.js</pre><div class="contentsignin">Copy after login</div></div>node_modules will be ignored.

File/Folderapp.vuecommonindex.htmlindex.jsrouterviews.gitignore#We don’t care about the specific code in these files for now, we will talk about it after webpack is configured.
Purpose
As the main file of vue
Put public code in it
Page template file
Project main entry file
Put the router file corresponding to vue
Put the view file
Ignore node_module

2. Configure webpack.config.js

    Install a series of packages:
  1. In order to run webpack, you need Installation
webpack
webpack-dev-server
Copy after login

In order to process vue single page files, install:

vue-loader
Copy after login

In order to process scss files and extract them from js, install:

node-sass
style-loader
css-loader
sass-loader
vue-style-loader
postcss
postcss-loader
autoprefixer
extract-text-webpack-plugin
Copy after login

In order to process image and font files , Installation:

file-loader
url-loader
Copy after login

To support advanced syntax-babel, Installation:

babel
babel-loader
babel-plugin-syntax-dynamic-import
babel-plugin-transform-object-rest-spread
babel-polyfill
babel-preset-env
Copy after login

To verify code format-eslint, Installation:

eslint
eslint-loader
eslint-plugin-html
babel-eslint
Copy after login

    Configure webpack .config.js file
  1. const webpack = require('webpack')
    const path = require('path')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
    // 为了抽离出两份CSS,创建两份ExtractTextPlugin
    // base作为基础的css,基本不变,所以,可以抽离出来充分利用浏览器缓存
    // app作为迭代的css,会经常改变
    const isProduction = process.env.NODE_ENV === 'production'
    const ExtractTextPlugin = require('extract-text-webpack-plugin')
    const extractBaseCSS =
      new ExtractTextPlugin(
        {
          filename:'static/css/base.[chunkhash:8].css',
          allChunks: true,
          disable: !isProduction // 开发环境下不抽离css
        }
      )
    const extractAppCSS
      = new ExtractTextPlugin(
        {
          filename:'static/css/app.[chunkhash:8].css',
          allChunks: true,
          disable: !isProduction // 开发环境下不抽离css
        }
      )
    
    // 减少路径书写
    function resolve(dir) {
      return path.join(__dirname, dir)
    }
    
    // 网站图标配置
    const favicon = resolve('favicon.ico')
    
    // __dirname: 总是返回被执行的 js 所在文件夹的绝对路径
    // __filename: 总是返回被执行的 js 的绝对路径
    // process.cwd(): 总是返回运行 node 命令时所在的文件夹的绝对路径
    const config = {
      // sourcemap 模式
      devtool: 'cheap-module-eval-source-map',
      // 入口
      entry: {
        app: [
          'babel-polyfill', // 这里是配合babel-present-env导入的动态babel-polyfill,因此npm需dev依赖
          resolve('app/index.js')
        ]
      },
      // 输出
      output: {
        path: resolve('dev'),
        filename: 'index.bundle.js'
      },
      resolve: {
        // 扩展名,比如import 'app.vue',扩展后只需要写成import 'app'就可以了
        extensions: ['.js', '.vue', '.scss', '.css'],
        // 取路径别名,方便在业务代码中import
        alias: {
          api: resolve('app/api/'),
          common: resolve('app/common/'),
          views: resolve('app/views/'),
          components: resolve('app/components/'),
          componentsBase: resolve('app/componentsBase/'),
          directives: resolve('app/directives/'),
          filters: resolve('app/filters/'),
          mixins: resolve('app/mixins/')
        }
      },
      // loaders处理
      module: {
        rules: [
          {
            test: /\.js$/,
            include: [resolve('app')],
            loader: [
              'babel-loader',
              'eslint-loader'
            ]
          },
          {
            test: /\.vue$/,
            exclude: /node_modules/,
            loader: 'vue-loader',
            options: {
              extractCSS: true,
              loaders: {
                scss: extractAppCSS.extract({
                  fallback: 'vue-style-loader',
                  use: [
                    {
                      loader: 'css-loader',
                      options: {
                        sourceMap: true
                      }
                    },
                    {
                      loader: 'postcss-loader',
                      options: {
                        sourceMap: true
                      }
                    },
                    {
                      loader: 'sass-loader',
                      options: {
                        sourceMap: true
                      }
                    }
                  ]
                })
              }
            }
          },
          {
            test: /\.(css|scss)$/,
            use: extractBaseCSS.extract({
              fallback: 'style-loader',
              use: [
                {
                  loader: 'css-loader',
                  options: {
                    sourceMap: true
                  }
                },
                {
                  loader: 'postcss-loader',
                  options: {
                    sourceMap: true
                  }
                },
                {
                  loader: 'sass-loader',
                  options: {
                    sourceMap: true
                  }
                }
              ]
            })
          },
          {
            test: /\.(png|jpe?g|gif|svg|ico)(\?.*)?$/,
            loader: 'url-loader',
            options: {
              limit: 8192,
              name: isProduction
                ? 'static/img/[name].[hash:8].[ext]'
                : 'static/img/[name].[ext]'
            }
          },
          {
            test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'url-loader',
            options: {
              limit: 8192,
              name: isProduction
                ? 'static/font/[name].[hash:8].[ext]'
                : 'static/font/[name].[ext]'
            }
          }
        ]
      },
      plugins: [
        // html 模板插件
        new HtmlWebpackPlugin({
          favicon,
          filename: 'index.html',
          template: resolve('app/index.html')
        }),
        // 抽离出css
        extractBaseCSS,
        extractAppCSS,
        // 热替换插件
        new webpack.HotModuleReplacementPlugin(),
        // 更友好地输出错误信息
        new FriendlyErrorsPlugin()
      ],
      devServer: {
        proxy: {
          // 凡是 `/api` 开头的 http 请求,都会被代理到 localhost:7777 上,由 koa 提供 mock 数据。
          // koa 代码在 ./mock 目录中,启动命令为 npm run mock。
          '/api': {
            target: 'http://localhost:7777', // 如果说联调了,将地址换成后端环境的地址就哦了
            secure: false
          }
        },
        host: '0.0.0.0',
        port: '9999',
        disableHostCheck: true, // 为了手机可以访问
        contentBase: resolve('dev'), // 本地服务器所加载的页面所在的目录
        // historyApiFallback: true, // 为了SPA应用服务
        inline: true, //实时刷新
        hot: true  // 使用热加载插件 HotModuleReplacementPlugin
      }
    }
    
    module.exports = {
      config: config,
      extractBaseCSS: extractBaseCSS,
      extractAppCSS: extractAppCSS
    }
    Copy after login
  2. Summary

This article mainly does three things:

    Easy to create Project structure
  1. After installing this article, and later using the npm package
  2. Webpack to configure the development environment
  3. Related recommendations:

VUE front-end cookie simple operation example sharing

The above is the detailed content of Vue front-end architecture learning (1). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the architecture and working principle of Spring Data JPA? What is the architecture and working principle of Spring Data JPA? Apr 17, 2024 pm 02:48 PM

SpringDataJPA is based on the JPA architecture and interacts with the database through mapping, ORM and transaction management. Its repository provides CRUD operations, and derived queries simplify database access. Additionally, it uses lazy loading to only retrieve data when necessary, thus improving performance.

1.3ms takes 1.3ms! Tsinghua's latest open source mobile neural network architecture RepViT 1.3ms takes 1.3ms! Tsinghua's latest open source mobile neural network architecture RepViT Mar 11, 2024 pm 12:07 PM

Paper address: https://arxiv.org/abs/2307.09283 Code address: https://github.com/THU-MIG/RepViTRepViT performs well in the mobile ViT architecture and shows significant advantages. Next, we explore the contributions of this study. It is mentioned in the article that lightweight ViTs generally perform better than lightweight CNNs on visual tasks, mainly due to their multi-head self-attention module (MSHA) that allows the model to learn global representations. However, the architectural differences between lightweight ViTs and lightweight CNNs have not been fully studied. In this study, the authors integrated lightweight ViTs into the effective

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Let's learn how to input the root number in Word together Let's learn how to input the root number in Word together Mar 19, 2024 pm 08:52 PM

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

How steep is the learning curve of golang framework architecture? How steep is the learning curve of golang framework architecture? Jun 05, 2024 pm 06:59 PM

The learning curve of the Go framework architecture depends on familiarity with the Go language and back-end development and the complexity of the chosen framework: a good understanding of the basics of the Go language. It helps to have backend development experience. Frameworks that differ in complexity lead to differences in learning curves.

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Hand-tearing Llama3 layer 1: Implementing llama3 from scratch Hand-tearing Llama3 layer 1: Implementing llama3 from scratch Jun 01, 2024 pm 05:45 PM

1. Architecture of Llama3 In this series of articles, we implement llama3 from scratch. The overall architecture of Llama3: Picture the model parameters of Llama3: Let's take a look at the actual values ​​of these parameters in the Llama3 model. Picture [1] Context window (context-window) When instantiating the LlaMa class, the variable max_seq_len defines context-window. There are other parameters in the class, but this parameter is most directly related to the transformer model. The max_seq_len here is 8K. Picture [2] Vocabulary-size and AttentionL

See all articles