1. 程式人生 > >分析vue-cli 啟動流程步驟

分析vue-cli 啟動流程步驟

啟動流程分析 

啟動入口: 找到package.json 包含工程依賴啟動命名直接查詢到 "scripts" 下的dev 啟動命令,可以看到命令啟動了webpack-dev-server 內建的服務,並且執行build/webpack.dev.conf.js 檔案

--progress 命令表示:檢視構建過程

--config 表示 自定義配置檔案

--inline 自動重新整理瀏覽器

步驟一:

webpack.dev.conf.js 指開發環境部署配置 配置原始碼分析

'use strict'
//工具方法,主要分辨css預解析器包括:less,sass等,以及合併css到一個主的css檔案中
const utils = require('./utils') 
const webpack = require('webpack')
//關於webpack 配置檔案的輸出與開發環境,如埠,靜態資源存放路徑等。詳細檢視config/index.js  配置說明
const config = require('../config')
//webpack 工具 大致用於合併兩個物件配置
const merge = require('webpack-merge')
const path = require('path')
//關鍵檔案 webpack 編譯前端工程的配置,如入口檔案地址,輸出檔案地址,別名,檔案預解析器
const baseWebpackConfig = require('./webpack.base.conf')
//webpack 拷貝外掛 配置某個起始目錄檔案拷貝到目標檔案中
const CopyWebpackPlugin = require('copy-webpack-plugin')
//webpack  模板配置 配置模板檔案預模板輸出後的名稱 用來資源自動插入  
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

//使用merge 合併資源配置 詳細配置檢視步驟二
const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,//是否開啟熱更新
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,//IP 地址
    port: PORT || config.dev.port,//埠
    open: config.dev.autoOpenBrowser,//是否自動開啟瀏覽器
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,//公用資源路徑
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env') //使用預設靜態自定義屬性
    }),
    new webpack.HotModuleReplacementPlugin(), //熱更新外掛
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    //模板外掛,自動引入資源到模板中
    new HtmlWebpackPlugin({
      filename: 'index.html',//設定生成模板的名稱
      template: './template/index.html',//模板的路徑
      inject: true //是否自動注入
    }),
    // copy custom static assets
    //拷貝檔案外掛,獲取本地下的static 拷貝到目標檔案to中
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),//拷貝源
        to: config.dev.assetsSubDirectory,//拷貝目的地
        ignore: ['.*'] //忽略無需拷貝的檔案
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))
        
      resolve(devWebpackConfig)
    }
  })
})

config/index.js 配置原始碼分析

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

//node 自帶路徑解析工具
const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',//靜態資源目錄
    assetsPublicPath: '/',//其他檔案工程目錄
    proxyTable: {},//設定代理
    /**
     * 代理案例
     * proxyTable: {
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
     */
    
    // Various Dev Server settings
    host: '0.0.0.0', // 主機IP地址
    port: 8080, // 埠
    autoOpenBrowser: false,//是否啟動自動開啟瀏覽器
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',//編譯原始碼map 目的是為了更快的排錯

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true 
  },

  build: {
    // Template for index.html
    // 構建打包的的檔案路徑
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    /**
     * 這應該指向包含應用程式的所有靜態資產的根目錄。例如,public/對於Rails / Laravel。
     */
    assetsRoot: path.resolve(__dirname, '../dist'),
    /**
     * 將webpack生成的資源嵌入此目錄中
     */
    assetsSubDirectory: 'static',
    /**
     * 這應該是build.assetsRoot通過HTTP提供服務的URL路徑。在大多數情況下,這將是root(/)。只有在後端框架為具有路徑字首的靜態資產提供服務時才更改此項
     */
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

webpack.base.conf.js  配置原始碼分析

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}



module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js' //入口檔案
  },
  output: {
    path: config.build.assetsRoot,//輸出路徑
    filename: '[name].js',//檔名
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath //開發環境輸出地址
      : config.dev.assetsPublicPath   //正式環境輸出地址
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'], //擴充套件檔名結尾
    //設定的別名
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
      '@static':resolve('static'),
      '@vuex':resolve('src/vuex'),
      '@components':resolve('src/components'),
      '@controller':resolve('src/controller'),
      '@filters':resolve('src/filters'),
      '@directive':resolve('src/directive'),
      '@utils':resolve('src/utils'),
      '@api':resolve('src/api')
    }
  },
   //預載入器
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig //通過不同環境, loader 選項引數
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}