Home >Web Front-end >JS Tutorial >Vue front-end architecture learning (1)

Vue front-end architecture learning (1)

小云云
小云云Original
2018-02-02 13:53:512284browse

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. <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>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

In order to process vue single page files, install:

vue-loader

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

In order to process image and font files , Installation:

file-loader
url-loader

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

To verify code format-eslint, Installation:

eslint
eslint-loader
eslint-plugin-html
babel-eslint

    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
    }
  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:
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