11:vue-cli腳手架

1.1 vue-cli基本使用

  官網: https://github.com/vuejs/vue-cli javascript

  一、簡介css

      vue-cli 是一個vue腳手架,能夠快速構造項目結構html

      vue-cli 自己集成了多種項目模板:前端

        simple 不多用,簡單vue

        webpack 包含ESLint代碼規範檢查和unit單元測試等java

        webpack-simple 沒有代碼規範檢查和單元測試node

      browserfy相似於vue-cliwebpack

        browserify 使用的也比較多git

        browserify-simplegithub

  二、安裝vue-cli,配置vue命令環境

        cnpm install vue-cli -g        # 全局安裝vue-cli

        vue --version                     # 查看vue-cli版本

        vue list

  三、初始化項目,生成項目模板

        vue init webpack-simple vue-cli-demo       # 生成項目模板:vue init 模板名 項目名

        cd vue-cli-demo

        cnpm install                                    # 切換到項目目錄安裝須要的包

        npm run dev                                   # 啓動測試服務

        npm run build                                 # 將項目打包輸出dist目錄,項目上線的話要將dist目錄拷貝到服務器上

 1.2 使用webpack模板的文件結構

  一、package.json

      1)package.json包含開發運行,項目打包,單元測試等命令,測試的東西先放一邊,看dev和build命令。

      2)運行」npm run dev」的時候執行的是build/dev-server.js文件,運行」npm run build」的時候執行的是build/build.js文件。

"scripts": {
  "dev": "node build/dev-server.js",
  "build": "node build/build.js",
  "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
  "e2e": "node test/e2e/runner.js",
  "test": "npm run unit && npm run e2e",
  "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs"
 }
package.json裏面的看到scripts字段

  二、build文件夾配置

  2.1 build/dev-server.js

# 1 檢查node和npm的版本
# 2 引入相關插件和配置
# 3 建立express服務器和webpack編譯器
# 4 配置開發中間件(webpack-dev-middleware)和熱重載中間件(webpack-hot-middleware)
# 5 掛載代理服務和中間件
# 6 配置靜態資源
# 7 啓動服務器監聽特定端口(8080)
# 8 自動打開瀏覽器並打開特定網址(localhost:8080)
dev-server.js主要做用
// 檢查NodeJS和npm的版本
require('./check-versions')()

// 獲取配置
var config = require('../config')
// 若是Node的環境變量中沒有設置當前的環境(NODE_ENV),則使用config中的配置做爲當前的環境
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}

// 一個能夠調用默認軟件打開網址、圖片、文件等內容的插件
// 這裏用它來調用默認瀏覽器打開dev-server監聽的端口,例如:localhost:8080
var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')

// 一個express中間件,用於將http請求代理到其餘服務器
// 例:localhost:8080/api/xxx  -->  localhost:3000/api/xxx
// 這裏使用該插件能夠將前端開發中涉及到的請求代理到API服務器上,方便與服務器對接
var proxyMiddleware = require('http-proxy-middleware')

// 根據 Node 環境來引入相應的 webpack 配置
var webpackConfig = process.env.NODE_ENV === 'testing'
  ? require('./webpack.prod.conf')
  : require('./webpack.dev.conf')

// dev-server 監聽的端口,默認爲config.dev.port設置的端口,即8080
var port = process.env.PORT || config.dev.port

// 用於判斷是否要自動打開瀏覽器的布爾變量,當配置文件中沒有設置自動打開瀏覽器的時候其值爲 false
var autoOpenBrowser = !!config.dev.autoOpenBrowser

// 定義 HTTP 代理表,代理到 API 服務器
var proxyTable = config.dev.proxyTable

// 建立1個 express 實例
var app = express()

// 根據webpack配置文件建立Compiler對象
var compiler = webpack(webpackConfig)

// webpack-dev-middleware使用compiler對象來對相應的文件進行編譯和綁定
// 編譯綁定後將獲得的產物存放在內存中而沒有寫進磁盤
// 將這個中間件交給express使用以後便可訪問這些編譯後的產品文件
var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  quiet: true
})

// webpack-hot-middleware,用於實現熱重載功能的中間件
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: () => {}
})

// 當html-webpack-plugin提交以後經過熱重載中間件發佈重載動做使得頁面重載
compiler.plugin('compilation', function (compilation) {
  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
    hotMiddleware.publish({ action: 'reload' })
    cb()
  })
})

// 將 proxyTable 中的代理請求配置掛在到express服務器上
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  // 格式化options,例如將'www.example.com'變成{ target: 'www.example.com' }
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})

// handle fallback for HTML5 history API
// 重定向不存在的URL,經常使用於SPA
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
// 使用webpack開發中間件
// 即將webpack編譯後輸出到內存中的文件資源掛到express服務器上
app.use(devMiddleware)

// enable hot-reload and state-preserving
// compilation error display
// 將熱重載中間件掛在到express服務器上
app.use(hotMiddleware)

// serve pure static assets
// 靜態資源的路徑
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)

// 將靜態資源掛到express服務器上
app.use(staticPath, express.static('./static'))

// 應用的地址信息,例如:http://localhost:8080
var uri = 'http://localhost:' + port

// webpack開發中間件合法(valid)以後輸出提示語到控制檯,代表服務器已啓動
devMiddleware.waitUntilValid(function () {
  console.log('> Listening at ' + uri + '\n')
})

// 啓動express服務器並監聽相應的端口(8080)
module.exports = app.listen(port, function (err) {
  if (err) {
    console.log(err)
    return
  }

  // when env is testing, don't need open it
  // 若是符合自動打開瀏覽器的條件,則經過opn插件調用系統默認瀏覽器打開對應的地址uri
  if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
    opn(uri)
  }
})
dev-server.js主要內容註釋

  2.2 build/webpack.base.conf.js

      1)從代碼中看到,dev-server使用的webpack配置來自build/webpack.dev.conf.js文件(測試環境下使用的是build/webpack.prod.conf.js,這裏暫時不考慮測試環境)。

      2)而build/webpack.dev.conf.js中又引用了webpack.base.conf.js,因此這裏先看webpack.base.conf.js。

# 1 配置webpack編譯入口
# 2 配置webpack輸出路徑和命名規則
# 3 配置模塊resolve規則
# 4 配置不一樣類型模塊的處理規則
webpack.base.conf.js做用
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')

// 給出正確的絕對路徑
function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

module.exports = {
  // 配置webpack編譯入口
  entry: {
    app: './src/main.js'
  },

  // 配置webpack輸出路徑和命名規則
  output: {
    // webpack輸出的目標文件夾路徑(例如:/dist)
    path: config.build.assetsRoot,
    // webpack輸出bundle文件命名格式
    filename: '[name].js',
    // webpack編譯輸出的發佈路徑
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },

  // 配置模塊resolve的規則
  resolve: {
    // 自動resolve的擴展名
    extensions: ['.js', '.vue', '.json'],
    // resolve模塊的時候要搜索的文件夾
    modules: [
      resolve('src'),
      resolve('node_modules')
    ],
    // 建立路徑別名,有了別名以後引用模塊更方便,例如
    // import Vue from 'vue/dist/vue.common.js'能夠寫成 import Vue from 'vue'
    alias: {
      'vue$': 'vue/dist/vue.common.js',
      'src': resolve('src'),
      'assets': resolve('src/assets'),
      'components': resolve('src/components')
    }
  },

  // 配置不一樣類型模塊的處理規則
  module: {
    rules: [
      {// 對src和test文件夾下的.js和.vue文件使用eslint-loader
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: "pre",
        include: [resolve('src'), resolve('test')],
        options: {
          formatter: require('eslint-friendly-formatter')
        }
      },
      {// 對全部.vue文件使用vue-loader
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {// 對src和test文件夾下的.js文件使用babel-loader
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      },
      {// 對圖片資源文件使用url-loader,query.name指明瞭輸出的命名規則
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {// 對字體資源文件使用url-loader,query.name指明瞭輸出的命名規則
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  }
}
代碼配置註釋

  2.3 build/webpack.dev.conf.js

      1)接下來看webpack.dev.conf.js,這裏面在webpack.base.conf的基礎上增長完善了開發環境下面的配置

# 1 將hot-reload相關的代碼添加到entry chunks
# 2 合併基礎的webpack配置
# 3 使用styleLoaders
# 4 配置Source Maps
# 5 配置webpack插件
主要完成下面操做
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')

// 一個能夠合併數組和對象的插件
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')

// 一個用於生成HTML文件並自動注入依賴文件(link/script)的webpack插件
var HtmlWebpackPlugin = require('html-webpack-plugin')

// 用於更友好地輸出webpack的警告、錯誤等信息
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

// 合併基礎的webpack配置
module.exports = merge(baseWebpackConfig, {
  // 配置樣式文件的處理規則,使用styleLoaders
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },

  // 配置Source Maps。在開發中使用cheap-module-eval-source-map更快
  devtool: '#cheap-module-eval-source-map',

  // 配置webpack插件
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.HotModuleReplacementPlugin(),
    // 後頁面中的報錯不會阻塞,可是會在編譯結束後報錯
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    new FriendlyErrorsPlugin()
  ]
})
代碼配置註釋

  2.4 build/utils.js

# 1 配置靜態資源路徑
# 2 生成cssLoaders用於加載.vue文件中的樣式
# 3 生成styleLoaders用於加載不在.vue文件中的單獨存在的樣式文件
utils主要完成下面3個操做

  2.5 build/vue-loader.conf.js

      1)vue-loader.conf則只配置了css加載器以及編譯css以後自動添加前綴。

var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'

module.exports = {
  // css加載器
  loaders: utils.cssLoaders({
    sourceMap: isProduction
      ? config.build.productionSourceMap
      : config.dev.cssSourceMap,
    extract: isProduction
  }),

  // 讓 vue-loader 知道須要對 audio 的 src 屬性的內容轉換爲模塊
  transformToRequire: {
    video: ‘src‘,
    source: ‘src‘,
    img: ‘src‘,
    image: ‘xlink:href‘
  }
}
代碼配置註釋

  2.6 build/build.js

      1)webpack編譯以後會輸出到配置裏面指定的目標文件夾;刪除目標文件夾以後再建立是爲了去除舊的內容,以避免產生不可預測的影響

# 1 loading動畫
# 2 刪除建立目標文件夾
# 3 webpack編譯
# 4 輸出信息
build.js主要完成下面操做
// 檢查NodeJS和npm的版本
require('./check-versions')()

process.env.NODE_ENV = 'production'

//ora插件,實現node.js 命令行環境的 loading效果, 和顯示各類狀態的圖標等
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')

// 用於在控制檯輸出帶顏色字體的插件
var chalk = require('chalk')

var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')

var spinner = ora('building for production...')
spinner.start()

//rimraf插件,每次啓動編譯或者打包以前,先把整個dist文件夾刪除,而後再從新生成dist
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  webpack(webpackConfig, function (err, stats) {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})
代碼配置註釋

  2.7 build/webpack.prod.conf.js

      1)構建的時候用到的webpack配置來自webpack.prod.conf.js,該配置一樣是在webpack.base.conf基礎上的進一步完善。

# 1 合併基礎的webpack配置
# 2 使用styleLoaders
# 3 配置webpack的輸出
# 4 配置webpack插件
# 5 gzip模式下的webpack插件配置
# 6 webpack-bundle分析
主要完成下面操做
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')

// 用於從webpack生成的bundle中提取文本到特定文件中的插件
// 能夠抽取出css,js文件將其與webpack輸出的bundle分離
var ExtractTextPlugin = require('extract-text-webpack-plugin')

var env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : config.build.env

// 合併基礎的webpack配置
var webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false,
  // 配置webpack的輸出
  output: {
    // 編譯輸出目錄
    path: config.build.assetsRoot,
    // 編譯輸出文件名格式
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    // 沒有指定輸出名的文件輸出的文件名格式
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },

  // 配置webpack插件
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),

    // 醜化壓縮代碼
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),

    // 抽離css文件
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),

    // 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
    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : 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'
    }),

    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module, count) {
        // 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',
      chunks: ['vendor']
    })
  ]
})

// gzip模式下須要引入compression插件進行壓縮
if (config.build.productionGzip) {
  var 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) {
  var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
代碼配置註釋

  2.8 build/check-versions.js

      1) check-version.js完成對node和npm的版本檢測。

// 用於在控制檯輸出帶顏色字體的插件
var chalk = require('chalk')

// 語義化版本檢查插件(The semantic version parser used by npm)
var semver = require('semver')

// 引入package.json
var packageConfig = require('../package.json')

// 開闢子進程執行指令cmd並返回結果
function exec (cmd) {
  return require('child_process').execSync(cmd).toString().trim()
}

// node和npm版本需求
var versionRequirements = [
  {
    name: 'node',
    currentVersion: semver.clean(process.version),
    versionRequirement: packageConfig.engines.node
  },
  {
    name: 'npm',
    currentVersion: exec('npm --version'),
    versionRequirement: packageConfig.engines.npm
  }
]

module.exports = function () {
  var warnings = []
  // 依次判斷版本是否符合要求
  for (var i = 0; i < versionRequirements.length; i++) {
    var mod = versionRequirements[i]
    if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
      warnings.push(mod.name + ': ' +
        chalk.red(mod.currentVersion) + ' should be ' +
        chalk.green(mod.versionRequirement)
      )
    }
  }

  // 若是有警告則將其輸出到控制檯
  if (warnings.length) {
    console.log('')
    console.log(chalk.yellow('To use this template, you must update following to modules:'))
    console.log()
    for (var i = 0; i < warnings.length; i++) {
      var warning = warnings[i]
      console.log('  ' + warning)
    }
    console.log()
    process.exit(1)
  }
}
代碼配置註釋

  三、config文件夾

  3.1 config/index.js

        1)config文件夾下最主要的文件就是index.js了,在這裏面描述了開發和構建兩種環境下的配置

        2)前面的build文件夾下也有很多文件引用了index.js裏面的配置。

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

module.exports = {
  // 構建產品時使用的配置
  build: {
    // webpack的編譯環境
    env: require('./prod.env'),
    // 編譯輸入的index.html文件
    index: path.resolve(__dirname, '../dist/index.html'),
    // webpack輸出的目標文件夾路徑
    assetsRoot: path.resolve(__dirname, '../dist'),
    // webpack編譯輸出的二級文件夾
    assetsSubDirectory: 'static',
    // webpack編譯輸出的發佈路徑
    assetsPublicPath: '/',
    // 使用SourceMap
    productionSourceMap: true,
    // 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
    // 默認不打開開啓gzip模式
    productionGzip: false,
    // gzip模式下須要壓縮的文件的擴展名
    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
  },
  // 開發過程當中使用的配置
  dev: {
    // webpack的編譯環境
    env: require('./dev.env'),
    // dev-server監聽的端口
    port: 8080,
    // 啓動dev-server以後自動打開瀏覽器
    autoOpenBrowser: true,
    // webpack編譯輸出的二級文件夾
    assetsSubDirectory: 'static',
    // webpack編譯輸出的發佈路徑
    assetsPublicPath: '/',
    // 請求代理表,在這裏能夠配置特定的請求代理到對應的API接口
    // 例如將'/api/xxx'代理到'www.example.com/api/xxx'
    proxyTable: {},
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    // 是否開啓 cssSourceMap
    cssSourceMap: false
  }
}
代碼配置註釋

    注:config/dev.env.js、config/prod.env.js,這兩個個文件就簡單設置了環境變量而已,沒什麼特別。

相關文章
相關標籤/搜索