天天看點

14. vue源碼入口+項目結構分析

一. vue源碼

我們安裝好vue以後, 如何了解vue的的代碼結構, 從哪裡下手呢?

1.1. vue源碼入口

vue的入口是package.json

14. vue源碼入口+項目結構分析

來分别看看是什麼含義

  • dependences:
"dependencies": {
    "vue": "^2.5.2"
  },
           

這段代碼告訴我們vue的版本: 2.5.2

  • engines
"engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
           

指定目前node的版本和npm的版本

  • devDependencies

    裡面是引入的各種loader

  • scripts
"scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "node build/build.js"
  },
           

這就是重點了。 我們npm run build、npm run dev都是執行這裡面的指令。 他告訴我們當執行build的時候是在執行那個檔案。

  1. dev: 讀取的配置檔案是build/webpack.dev.conf.js
  2. build: 讀取的配置檔案是buld/build.js

1.2.項目檔案的結構

先來看看項目的整體目錄結構

14. vue源碼入口+項目結構分析

1.2.1. webpack相關配置

1.2.1.1 webpack.dev.config.js是本地開發環境讀取配置檔案。

'use strict'
// 定義變量, 生産環境和開發環境差別定義
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
// 引入公共配置
const baseWebpackConfig = require('./webpack.base.conf')
/**
 * 引入插件
 */
// 版權插件
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 打包html到dist檔案下, 并自動引入main.js檔案
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,
    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: 'index.html',
      inject: true
    }),
    // copy custom static assets
    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)
    }
  })
})


           
  • webpack.base.conf: 引入了基礎項目配置。 公共的配置檔案(開發和生産都會使用到的配置檔案)都寫到這裡
  • 引入插件: 版權插件、html檔案打包插件、有好錯題提示插件
  • 引入merge包, 将基礎配置檔案和目前檔案合并。

1.2.1.2 build.js是build打包時讀取的配置檔案

'use strict'
require('./check-versions')()

process.env.NODE_ENV = 'production'

const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
// 引入了prod配置檔案
const webpackConfig = require('./webpack.prod.conf')

...
           

我們看到build.js引入了webpack.prod.conf配置檔案

下面就來看看webpack.prod.conf配置檔案都有哪些内容

'use strict'
// 生産環境個性化配置
const path = require('path')
const utils = require('./utils')
// 引入webpack打包工具
const webpack = require('webpack')
const config = require('../config')
// 引入配置合并工具
const merge = require('webpack-merge')
// 引入基礎配置檔案
const baseWebpackConfig = require('./webpack.base.conf')
// 引入版權配置插件
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 引入html配置合并
const HtmlWebpackPlugin = require('html-webpack-plugin')
// 引入text打包工具
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// 引入css打包工具
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 引入js壓縮工具
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

// 引入生産環境的配置檔案
const env = require('../config/prod.env')

// merge: 将基礎配置 + 生産的個性化配置合并
const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  // 生成環境需要使用的插件
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      // Setting the following option to `false` will not extract CSS from codesplit chunks.
      // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
      // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
      // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    // html打包插件: 比如:将index.html打包到dist檔案夾中.并自動引入bundle.js檔案
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    // This instance extracts shared chunks from code splitted chunks and bundles them
    // in a separate chunk, similar to the vendor chunk
    // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
           
  • 這prod.config.js中引入了webpack.base.conf
  • 引入了一些插件: 版權配置插件, html打包插件,text打包工具、css打包壓縮工具、js壓縮工具。
  • 讀取了config/prod.env配置檔案。
  • 使用merge合并基礎配置

1.2.2 .babelrc配置檔案:ES代碼相關轉化配置

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": ["transform-vue-jsx", "transform-runtime"]
}
           

這是将es6的文法轉換成es5. 轉換的目标是什麼呢

"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
           
  1. 市場佔有率大于1%
  2. 轉換浏覽器的最後兩個版本
  3. ie8以下的版本不轉化

1.2.3 .editorconfig文本編輯相關配置

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

           
  • charset: 配置文本的字元編碼格式
  • indent_style: 預設的縮進方式是空格
  • indent_size: 縮進空格數是2個
  • end_of_line: 尾部處理方式
  • insert_final_newline: 尾部自動增加一個單行
  • trim_trailing_whitespace: 是否自動格式化空格

1.2.4 .eslintrc.js esLint相關的設定

esLint格式化内容配置, 我們可以啟動或者關閉eslint.

1.3. vue通路入口

vue的通路入口是index.html, 當我們執行

npm run dev
           

的時候, 其實是将檔案打包的過程, 和npm run build的差別是, 它是将檔案打包到記憶體。 然後運作在本地伺服器。而npm run build是打包到磁盤dist檔案夾

1.3.1 通路入口

vue通路的入口是main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

           
  • 引入了vue
  • 引入了./App.vue, 目前目錄的App.vue配置檔案
  • 目前vue的作用dom元素是id="app"的元素
  • 引入了App元件。 App元件,定義在App.vue中
  • 使用App元件替代id="app"的元素。

下面來看看App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <HelloWorld/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
           
  • 首先引入了HelloWorld元件
import HelloWorld from './components/HelloWorld'
           
  • 将元件注冊到名為App的元件中
  • 在模闆中引入HelloWorld元件

然後,我們就看到vue首頁的效果了。了解源碼入口,友善我們後續代碼.

14. vue源碼入口+項目結構分析