vue-cli2、vue-cli3腳手架詳細講解

轉載自 vue-cli2、vue-cli3腳手架詳細講解

前言:

       vue腳手架指的是vue-cli它是vue官方提供的一個快速構建單頁面(SPA)環境配置的工具,cli 就是(command-line-interface  ) 命令行界面 。vue-cli是基於node環境利用webpack對文件進行編譯、打包、壓縮、es6轉es5等一系列操作。目前vue-cli已經升級到了3.0版本,3.0所需的webpack版本是4.xxx,2.0版本目前也很流行,2.0所需的webpack版本是3.xxx,我們來講講兩者的配置:

(1)Vue2.0

一.安裝node.js環境:

    去node官網下載node.js並安裝(http://nodejs.cn/download/)。安裝完成後可以在終端執行 node -v查看node 是否安裝成功,下圖是安裝成功的提示,顯示出當前安裝的node的版本號。

  

 

二.全局安裝webpack

    爲了在其他任何目錄下都能使用到webpack,進行全局安裝,執行npm install [email protected] -g 命令,npm 是Node集成的工具 npm install 是從github上下載webpack最新的包,“@3.12.0”表示安裝指定的版本,因爲現在已經升級到了4.0版本,如果不指定版本版本號就會安裝最新的版本,同時vue-cli2需要的是3.xxx的版本,所以我們指定了一個固定版本,如果不指定則不需要,"-g" 全稱是 " global (全局) "  表示全局安裝。檢查是否安裝成功終端執行“webpack -v”或者"webpack --version",如果顯示具體的版本號則表示安裝成功。

 

 

 三.全局安裝 vue-cli2

   執行“npm install  @vue/cli  -g”命令進行安裝。“npm install  @vue/cli  -g” 命令是腳手架3的,“npm install vue-cli -g”命令纔是腳手架3的,腳手架2和腳手架3是不相同的,如果現在使用 “npm install vue-cli -g”命令進行安裝的話,下次使用腳手架3的時候就得卸載腳手架2,安裝腳手架3,爲了減少不必要的操作我們執行 “npm install  @vue/cli  -g ” 命令進行安裝,然後再執行 “npm install @vue-cli-init -g ” 將腳手架2下載下來,在此環境下既可以安裝腳手架2的模板,有可以安裝腳手架3的模板。  檢查是否安裝成功終端執行“vue -V”或者"vue --version",如果顯示具體的版本號則表示安裝成功。具體安裝方式查看官網(https://cli.vuejs.org/zh/)。

 

 

四.初始化項目

  進入到自己要安裝項目的文件夾目錄,我這裏是 “D:\webpackProject\vue-cli2> ”  執行 “vue  init  webpack  vue-cli2-project ” 命令,出現如下圖提示 ,“vue-cli2-project” 是我們的項目文件夾的名字,就是最終顯示在index.html中的title標籤裏和package.json中的,也可以自己進行修改,我們一般不會去改,直接按回車鍵進行下一步。

         

  “? Project description (A Vue.js project)”  是項目的描述,自己可以修改或者使用默認的,我們一般使用默認的直接按回車鍵進行下一步,

這裏是作者的信息,我們使用默認的,直接下一步,

這裏有兩個選項:Runtime +  Compiler 和Runtime-only ,Runtime-only要比Runtime +  Compiler 輕大約6KB,而且效率要高, 按上下鍵可以進行選擇,默認是第一個,選擇好後按回車鍵進行下一步, 

這一步是詢問是否使用vue-router(路由),因爲在項目中我們會用到所以這裏按Y 鍵,進行下一步,

   這一步是詢問是否使用ESLint(語法檢查器),ES (ecscript) 即 javascript ,lint 限制的意思,也就是 javascript語法限制器,使得你的語法更加規範,如果你的語法不規範編輯器就會報錯,你可能在開發過程中因爲一個空格導致語法不規範進而報錯(其實你的代碼沒有問題的),所以對於初學者不建議使用此語法,所以我們選擇 n,並進行下一步操作,

這一步是詢問是否使用單元測試,這個用的人比較少,所以我們不適用,輸入n並進行一下步,

  

這一步詢問是否要進行e2e(端到端測試),是一個自動化測試的框架,這裏我們就不使用了,直接輸入n,進行下一步:

    

這裏詢問我們管理項目是用npm 還是yarn ,這裏我們使用npm ,直接回車,接下來就是等待安裝node_modules。下圖表示安裝完成:

執行 cd vue-cli2-project 進入到我們的項目目錄下,然後執行 npm run dev 命令進行啓動我們的項目,下圖是我們的項目目錄:

 

五、 項目目錄介紹:

     1、build  文件夾:webpack的一些相關配置;

     2、config  文件夾:項目開發環境和生產環境的一些相關配置;

     3、node_modules  文件夾 :這裏存放的是安裝包,比如webpack、第三方插件庫、項目的依賴文件;

     4、src  文件夾:我們將要寫的代碼放在這裏面,打包上線時會進行編譯、壓縮等操作。

     5、static 文件夾:這裏存放的是一些靜態文件比如圖片、css文件、不需要進行壓縮的js文件,打包時這個文件夾將原封不動的放到dist(打包時自動生產的文件夾)文件夾下面。

     6、.babelrc 文件:ES6語法編譯配置,主要是將ES 轉成ES 需要適配那些瀏覽器

     7、.editorconfig 文件:定義代碼格式,對代碼的風格進行一個統一。

        8、.gitignore 文件:git上傳需要忽略的文件格式

     9、  .postcssrc.js 文件:postcss配置文件

                 10、 index.html  文件:要進行訪問的首頁面

                 11、package-lock.json 文件:鎖定依賴模塊和子模塊的版本號

                 12、package.json 文件:項目基本信息,包依賴信息等

                 13、README.md  文件:項目說明文件

文件詳解:

1、package.json 文件:當我們在命令行時 npm run dev 的時候程序執行的是package.json文件的“script”腳本里的“dev”命令;

這段代碼的意思是啓動 “webpack-dev-server” 服務器,“--inline” 是 重新加載改變的部分,不會刷新頁面,--progress是啓動項目時顯示進度,“--config build/webpack.dev.conf.js” 是執行build下面的webpack.dev.conf.js配置文件。我們可以添加其他屬性比如 “--open” 是啓動項目後自動在瀏覽器打開項目,其它配置可以查看相關文檔(https://www.webpackjs.com/configuration/dev-server/#devserver)。“start” 和“dev”的作用是一樣的,“build” 的作用是執行 build下的build.js文件,將當前的項目進行打包。打包後生成一個dist文件夾,放在其裏面。webpack.dev.conf.js文件是我們在開發環境下的webpack配置文件,打開次文件,內容如下:

 

2.、build/webpack.dev.conf.js 文件:

'use strict'
const utils = require('./utils')         //引入的工具包
const webpack = require('webpack')      //引入webpack包
const config = require('../config')     //引入 config下的index.js文件
const merge = require('webpack-merge')  //合併配置文件
const path = require('path')            //node的path模塊,對路徑進行處理
const baseWebpackConfig = require('./webpack.base.conf') //將生產和開發環境下共用的配置文件進行了抽離形成了改文件
const CopyWebpackPlugin = require('copy-webpack-plugin') //拷貝插件
const HtmlWebpackPlugin = require('html-webpack-plugin')  //加載html模塊
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') //友好的錯誤提示插件
const portfinder = require('portfinder')   //在當前機器上找一個可打開的端口號,默認是8080,如果端口號被佔用則重新尋找可打開的端口號。

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

const devWebpackConfig = merge(baseWebpackConfig, {   //利用merge插件將 baseWebpackConfig 配置與當前配置進行合併
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })  //引入utils中一些css-loader和postcss-loader
  },

  devtool: config.dev.devtool, //控制是否生成以及如何生成源碼映射,這裏引入的是config下的index.js的 “devtool: 'cheap-module-eval-source-map'”,

  // these devServer options should be customized in /config/index.js
  // dev-server的配置
  devServer: {
    clientLogLevel: 'warning',      //當使用inline mode,devTools的命令行中將會顯示一些調試信息
    historyApiFallback: {           //當使用 HTML5 History API 時,任意的 404 響應都可能需要被替代爲 index.html
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,            //啓用 webpack 的模塊熱替換特性
    contentBase: false,   // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,   //要開啓的域名,可在package.json中的“dev”命令中進行配置
    port: PORT || config.dev.port,   //要開啓的端口號,可在package.json中的“dev”命令中進行配置
    open: config.dev.autoOpenBrowser,//是否自動在瀏覽器中打開,可在package.json中的“dev”命令中進行配置
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath, //
    proxy: config.dev.proxyTable,   //當出現跨域時設置代理,這裏引入了config下的index.js的配置
    quiet: true, // necessary for FriendlyErrorsPlugin  啓用 quiet 後,除了初始啓動信息之外的任何內容都不會被打印到控制檯。這也意味着來自 webpack 的錯誤或警告在控制檯不可見
    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(),          // 這個插件的作用是在熱加載時直接返回更新文件名,而不是文件的id。
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({   //打包時生成index.html並且自動加載app.js文件  <!-- built files will be auto injected -->
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'), //將static整個文件夾原封不動地拷貝到dist目錄下。
        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.js的配置(公共配置)與本文件配置進行合併,再看一下 webpack.base.conf.js 文件:

  

3、build/webpack.base.conf.js 文件   

'use strict'
const path = require('path') //node的path模塊,對路徑進行處理
const utils = require('./utils') //引入的工具包
const config = require('../config')//引入 config下的index.js文件
const vueLoaderConfig = require('./vue-loader.conf') //根據NODE_ENV這個變量分析是否是生產環境,然後根據不同的環境來加載,判斷是否開啓了sourceMap的功能

function resolve (dir) {
  return path.join(__dirname, '..', dir) //對路徑進行處理,獲取到絕對路徑
}



module.exports = {
  context: path.resolve(__dirname, '../'), //對路徑進行處理,跳到當前項目的根目錄下
  entry: {     //入口文件,即項目要引入哪個js文件
    app: './src/main.js'        //因爲 context 中已經跳到了當前項目的根目錄下,所以這裏的路徑是以 ./src 開頭
  },
  output: { //輸出文件,即項目要輸出到哪裏去
    path: config.build.assetsRoot,  //輸出到根目錄下的dist問價夾裏,具體地址可以在config下的index.js中進行修改
    filename: '[name].js',      //以文件的原始名輸出
    publicPath: process.env.NODE_ENV === 'production'   //根據process.env.NODE_ENV 來判斷是生產模式還是開發模式,將最終打包的項目要放到服務器的什麼地方,默認是 '/' 即服務器的根目錄下。
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],  //簡化一些文件名,引入文件時可以不帶後綴名
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),          //簡化文件的引入問題,如:本文件中要引入 src下的common裏的demo.js,你就可以這樣引入:@/common/demo.js
    }
  },
  module: {

    rules: [
      // 配置各種loader,來處理對應的文件
      {
        test: /\.vue$/,   //使用vue-loader處理以.vue結束的文件
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,    //使用babel-loader處理以.js結束的文件,即js文件
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,   //使用url-loader處理各種格式的圖片資源,最大限制10000KB,這裏不處理src同級目錄下的static裏的圖片。
        loader: 'url-loader',
        options: {
          limit: 10000,   
          name: utils.assetsPath('img/[name].[hash:7].[ext]')  //將處理後的放在img文件下,並且加上7位hash值。
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,   //使用url-loader處理視頻文件。
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,            //使用url-loader處理字體文件。
        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'
  }
}

  主要的說明已經註釋在了文件中,這個問價的主要配置有entry(入口文件)、output(輸出文件)、loader ,這些都是必備的,而一些plugins(插件)已經在對應的環境文件(webpack.dev.config.js、webpack.prod.config.js)中進行了配置,再看一下webpack.prod.config.js文件:

 4、build/webpack.prod.config.js:  

'use strict'
const path = require('path')
const utils = require('./utils')
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')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin') //抽離css樣式,防止將樣式打包在js中引起頁面樣式加載錯亂的現象
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')//主要是用來壓縮css文件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')  //對js文件進行壓縮

const env = require('../config/prod.env')

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,  //使用sourceMap將錯誤消息位置映射到模塊(這會減慢編譯速度)。
      parallel: true        //啓用/禁用多進程並行運行,啓用後會提高構建速度
    }),

    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
  
      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 } }  //判斷是否生成內聯映射,如果生成則會生成一個source-map文件
        : { 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
    new HtmlWebpackPlugin({
      filename: config.build.index, //將會生成一個index.html文件,放到dist文件下
      template: 'index.html',
      inject: true,                //將所有js資源放在body標籤的底部
      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'    //允許控制塊在包含到HTML之前按照依賴排序
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(), //該插件會根據模塊的相對路徑生成一個四位數的hash作爲模塊id, 建議用於生產環境。
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),//啓用作用域提升,讓代碼文件更小、運行的更快
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({ //主要是用來提取第三方庫和公共模塊,避免首屏加載的bundle文件或者按需加載的bundle文件體積過大,從而導致加載時間過長
      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

當我們執行 npm run build 打包時執行的是: build下的build.js文件,build.js中引入了webpack.prod.config.js,因此build.js纔是生產環境所需的webpack文件。

5、build/build.js:

'use strict'
require('./check-versions')() //該文件用於檢測node和npm的版本,實現版本依賴

process.env.NODE_ENV = 'production'

const ora = require('ora')    //在node端加載動畫模塊
const rm = require('rimraf')  //用來刪除文件和文件夾的
const path = require('path')
const chalk = require('chalk') //修改控制檯中字符串的樣式
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf') 

const spinner = ora('building for production...') //設置一個動畫的內容爲 "building for production..."
spinner.start()   //加載動畫

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {  //利用 rm 模塊先刪除dist文件再生成新文件,因爲有時候會使用hash來命名,刪除整個文件可避免冗餘
  if (err) throw err
  webpack(webpackConfig, (err, stats) => {   //將一下配置內容與 webpack.prod.conf.js中的配置進行合併
    spinner.stop()  //停止動畫
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    if (stats.hasErrors()) {
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }

    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'
    ))
  })
})

 

6、build/check-versions.js:  檢測node和npm的版本,實現版本依賴

'use strict'
// 該文件用於檢測node和npm的版本,實現版本依賴
const chalk = require('chalk')  //node.js中的模塊,作用是修改控制檯中字符串的樣式
const semver = require('semver')  //node.js中的模塊,對版本進行檢查
const packageConfig = require('../package.json') //引入page.json文件
const shell = require('shelljs')

function exec (cmd) {
  //通過child_process模塊的新建子進程,執行 Unix 系統命令後轉成沒有空格的字符串
  return require('child_process').execSync(cmd).toString().trim()
}

const versionRequirements = [
  {
    name: 'node',
    currentVersion: semver.clean(process.version),  //使用semver格式化版本
    versionRequirement: packageConfig.engines.node //獲取package.json中設置的node版本
  }
]

if (shell.which('npm')) {
  versionRequirements.push({
    name: 'npm',
    currentVersion: exec('npm --version'),   //自動調用npm --version命令,並且把參數返回給exec函數,從而獲取純淨的版本號
    versionRequirement: packageConfig.engines.npm
  })
}

module.exports = function () {
  const warnings = []

  for (let i = 0; i < versionRequirements.length; i++) {
    const mod = versionRequirements[i]

    if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
      //如果上面的版本號不符合package.json文件中指定的版本號,就執行下面錯誤提示的代碼
      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 (let i = 0; i < warnings.length; i++) {
      const warning = warnings[i]
      console.log('  ' + warning)
    }

    console.log()
    process.exit(1)
  }
}

 

7、build/vue-loader.conf.js:

'use strict'

//根據NODE_ENV這個變量分析是否是生產環境,然後根據不同的環境來加載,判斷是否開啓了sourceMap的功能。方便之後在cssLoaders中加上sourceMap功能。然後判斷是否設置了cacheBusting屬性,
// 它指的是緩存破壞,特別是進行sourceMap debug時,設置成false是非常有幫助的。最後就是一個轉化請求的內容,video、source、img、image等的屬性進行配置。具體的還是需要去了解vue-loader這個
// webpack的loader加載器

const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap
//處理項目中的css文件,生產環境和測試環境默認是打開sourceMap,而extract中的提取樣式到單獨文件只有在生產環境中才需要
module.exports = {
  loaders: utils.cssLoaders({
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled, 
  cacheBusting: config.dev.cacheBusting,
  transformToRequire: {//在模版編譯過程中,編譯器可以將某些屬性,如 src 路徑,轉換爲require調用,以便目標資源可以由 webpack 處理.
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  }
}

8、build/utils:

'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin') ////抽離css樣式,防止將樣式打包在js中引起頁面樣式加載錯亂的現象
const packageConfig = require('../package.json')


//導出文件的位置,根據環境判斷開發環境和生產環境,爲config文件中index.js文件中定義的build.assetsSubDirectory或
exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory

  return path.posix.join(assetsSubDirectory, _path)
}

//使用了css-loader和postcssLoader,通過options.usePostCSS屬性來判斷是否使用postcssLoader中壓縮等方法
exports.cssLoaders = function (options) {   //導出css-loader
  options = options || {}

  const cssLoader = {
    loader: 'css-loader',
    options: {
      sourceMap: options.sourceMap 
    }
  }

  const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] //根據傳入的參數判斷是使用cssLoader、 postcssLoader還是隻使用 cssLoader

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {  //將後面的兩個對象合併後再進行復制
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  const output = []
  const loaders = exports.cssLoaders(options)

  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }

  return output
}

exports.createNotifierCallback = () => {
  const notifier = require('node-notifier')

  return (severity, errors) => {
    if (severity !== 'error') return

    const error = errors[0]
    const filename = error.file && error.file.split('!').pop()

    notifier.notify({
      title: packageConfig.name,
      message: severity + ': ' + error.name,
      subtitle: filename || '',
      icon: path.join(__dirname, 'logo.png')
    })
  }
}

 

9、config/index.js: 生產 和 開發 環境下webpack的公共配置文件  

const path = require('path')

module.exports = {
  dev: {  //開發環境下的配置

    // Paths
    assetsSubDirectory: 'static', //子目錄,一般存放css,js,image等文件
    assetsPublicPath: '/', //根目錄
    proxyTable: {},  //在這裏使用代理解決跨越問題

    // Various Dev Server settings
    host: 'localhost', // 域名
    port: 8080, // 開啓的端口號,默認是8080
    autoOpenBrowser: true, //是否自動打開瀏覽器
    errorOverlay: true,  //瀏覽器錯誤提示
    notifyOnErrors: true, //跨平臺錯誤提示
    poll: false, // 使用文件系統(file system)獲取文件改動的通知devServer.watchOptions

    
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',//增加調試,該屬性爲原始源代碼(僅限行)不可在生產環境中使用

    cacheBusting: true,//使緩存失效

    cssSourceMap: true   //代碼壓縮後進行調bug定位將非常困難,於是引入sourcemap記錄壓縮前後的位置信息記錄,當產生錯誤時直接定位到未壓縮前的位置,將大大的方便我們調試
  },

  build: { //生產發環境下的配置
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'), //index.html編譯後生成的位置和名字

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),//編譯後存放生成環境代碼的位置
    assetsSubDirectory: 'static',  //js,css,images存放文件夾名
    assetsPublicPath: '/',  //發佈的根目錄,通常本地打包dist後打開文件會報錯,此處修改爲./。如果是上線的文件,可根據文件存放位置進行更改路徑

    productionSourceMap: true,
  
    devtool: '#source-map',

    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    bundleAnalyzerReport: process.env.npm_config_report
  }
}

 

10、config/dev.env.js: 

'use strict'
// 當在開發環境下引用(webpack.dev.config.js中的plugin中)的是此文件,次文件指定了 開發模式: node-env ,
//利用merge方法將prod.env.js與本文件進行合併,在開發模式下輸出 NODE_ENV="development"

    //webpack.dev.config.js中的plugin引用如下:
    // new webpack.DefinePlugin({
    //   'process.env': require('../config/dev.env')
    // })
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
})

11、config/prod.env.js: 

'use strict'
// 在生產模式下調用此文件
// 在webpack.prod.config.js中的plugin中引用如下:
      //const env = require('../config/prod.env')
      // new webpack.DefinePlugin({
      //   'process.env': env
      // }),
module.exports = {
  NODE_ENV: '"production"'
}

12 、node_modules文件夾:該文件夾下存放的是node的一些依賴模塊,比如:require模塊、path模塊、http-proxy-middleware模塊,還有一些我們通過npm安裝的插件模塊,比如vue、md5、vue-cli、ivew等。

13.、src文件夾: 該文件夾下面存放的是我們項目代碼以及一些文件,components文件夾存放了我們自己寫的組件,router文件夾裏面存放了路由配置,mian.js是整個項目的入口js,在build文件夾下的webpack.dev.config.js中的entry中有配置(

 app: './src/main.js')。App.vue文件是項目的首頁面。

 

 

vue 3.0

 1.安裝vue3:新建一個文件夾,進入該文件夾下,執行 vue create   ( 項目名稱) , 如下圖:

vuecli3爲項目名稱,進入下一步,

   上面提示:請選擇一個配置。下面有3個選項,第一個 “myset  ” 是 我自己手動選擇的配置,你們第一個安裝你沒有這個選項,如果選擇了第3個通過手動選擇後,下次再安裝時會出現在這裏,第二個 “default”是默認的,第3個是 手動選擇。我們先選擇第3個,進入下一步,

   

這裏要我們選擇一個配置,按住上下鍵進行調轉,空格鍵進行選中或者取消,

   

  這一步詢問的是 把項目的配置文件放在獨立的配置文件中還是放在package.json文件中,這裏我們選擇第一個,方便我們以後的修改,進行下一步

 這裏詢問的是我們手動配置要不要進行保存,以便下次使用,也就是安裝第一步的時候的選擇,輸入 y,

這裏要輸入的是要保存的命字,進行一下步安裝,

安裝完成。

 

啓動項目

                      

這是vue3的項目結構,顯然和vue2的結構不一樣,沒有了config文件夾而且還多了一個.git文件,方便我們項目管理,其中public相當於vue2中的static靜態文件夾,相同文件我就不說了,我只說一下不同文件。

我們先看一下package.json文件,

 

   

開發依賴少了很多,因爲vue3.0講究的是 0 配置,因爲不顯示的這些文件不需要我們去改,我們通過npm安裝的依賴會存在哪裏呢?

  這裏我安裝了2個依賴,很顯然是放在package.json文件下的,方便我們去管理自己的依賴。那默認的那些依賴存在哪裏呢?

。其實是通過 "@vue/cli-service": "^4.0.0",去管理我們的依賴的,在 “node_modules”  =>  “@vue”  => cli-service => package.json,這裏面就是隱藏的依賴。

vue2中的config文件夾隱藏到了“node_modules”  =>  “@vue”  => cli-service => webpack.config.js中,而在webpack.config.js中有這一行代碼:

所以再找到Service.js文件,

const fs = require('fs')
const path = require('path')
const debug = require('debug')
const chalk = require('chalk')
const readPkg = require('read-pkg')
const merge = require('webpack-merge')
const Config = require('webpack-chain')
const PluginAPI = require('./PluginAPI')
const dotenv = require('dotenv')
const dotenvExpand = require('dotenv-expand')
const defaultsDeep = require('lodash.defaultsdeep')
const { warn, error, isPlugin, resolvePluginId, loadModule } = require('@vue/cli-shared-utils')

const { defaults, validate } = require('./options')

module.exports = class Service {
  constructor (context, { plugins, pkg, inlineOptions, useBuiltIn } = {}) {
    process.VUE_CLI_SERVICE = this
    this.initialized = false
    this.context = context
    this.inlineOptions = inlineOptions
    this.webpackChainFns = []
    this.webpackRawConfigFns = []
    this.devServerConfigFns = []
    this.commands = {}
    // Folder containing the target package.json for plugins
    this.pkgContext = context
    // package.json containing the plugins
    this.pkg = this.resolvePkg(pkg)
    // If there are inline plugins, they will be used instead of those
    // found in package.json.
    // When useBuiltIn === false, built-in plugins are disabled. This is mostly
    // for testing.
    this.plugins = this.resolvePlugins(plugins, useBuiltIn)
    // pluginsToSkip will be populated during run()
    this.pluginsToSkip = new Set()
    // resolve the default mode to use for each command
    // this is provided by plugins as module.exports.defaultModes
    // so we can get the information without actually applying the plugin.
    this.modes = this.plugins.reduce((modes, { apply: { defaultModes }}) => {
      return Object.assign(modes, defaultModes)
    }, {})
  }

  resolvePkg (inlinePkg, context = this.context) {
    if (inlinePkg) {
      return inlinePkg
    } else if (fs.existsSync(path.join(context, 'package.json'))) {
      const pkg = readPkg.sync({ cwd: context })
      if (pkg.vuePlugins && pkg.vuePlugins.resolveFrom) {
        this.pkgContext = path.resolve(context, pkg.vuePlugins.resolveFrom)
        return this.resolvePkg(null, this.pkgContext)
      }
      return pkg
    } else {
      return {}
    }
  }

  init (mode = process.env.VUE_CLI_MODE) {
    if (this.initialized) {
      return
    }
    this.initialized = true
    this.mode = mode

    // load mode .env
    if (mode) {
      this.loadEnv(mode)
    }
    // load base .env
    this.loadEnv()

    // load user config
    const userOptions = this.loadUserOptions()
    this.projectOptions = defaultsDeep(userOptions, defaults())

    debug('vue:project-config')(this.projectOptions)

    // apply plugins.
    this.plugins.forEach(({ id, apply }) => {
      if (this.pluginsToSkip.has(id)) return
      apply(new PluginAPI(id, this), this.projectOptions)
    })

    // apply webpack configs from project config file
    if (this.projectOptions.chainWebpack) {
      this.webpackChainFns.push(this.projectOptions.chainWebpack)
    }
    if (this.projectOptions.configureWebpack) {
      this.webpackRawConfigFns.push(this.projectOptions.configureWebpack)
    }
  }

  loadEnv (mode) {
    const logger = debug('vue:env')
    const basePath = path.resolve(this.context, `.env${mode ? `.${mode}` : ``}`)
    const localPath = `${basePath}.local`

    const load = envPath => {
      try {
        const env = dotenv.config({ path: envPath, debug: process.env.DEBUG })
        dotenvExpand(env)
        logger(envPath, env)
      } catch (err) {
        // only ignore error if file is not found
        if (err.toString().indexOf('ENOENT') < 0) {
          error(err)
        }
      }
    }

    load(localPath)
    load(basePath)

    // by default, NODE_ENV and BABEL_ENV are set to "development" unless mode
    // is production or test. However the value in .env files will take higher
    // priority.
    if (mode) {
      // always set NODE_ENV during tests
      // as that is necessary for tests to not be affected by each other
      const shouldForceDefaultEnv = (
        process.env.VUE_CLI_TEST &&
        !process.env.VUE_CLI_TEST_TESTING_ENV
      )
      const defaultNodeEnv = (mode === 'production' || mode === 'test')
        ? mode
        : 'development'
      if (shouldForceDefaultEnv || process.env.NODE_ENV == null) {
        process.env.NODE_ENV = defaultNodeEnv
      }
      if (shouldForceDefaultEnv || process.env.BABEL_ENV == null) {
        process.env.BABEL_ENV = defaultNodeEnv
      }
    }
  }

  setPluginsToSkip (args) {
    const skipPlugins = args['skip-plugins']
    const pluginsToSkip = skipPlugins
      ? new Set(skipPlugins.split(',').map(id => resolvePluginId(id)))
      : new Set()

    this.pluginsToSkip = pluginsToSkip
  }

  resolvePlugins (inlinePlugins, useBuiltIn) {
    const idToPlugin = id => ({
      id: id.replace(/^.\//, 'built-in:'),
      apply: require(id)
    })

    let plugins

    const builtInPlugins = [
      './commands/serve',
      './commands/build',
      './commands/inspect',
      './commands/help',
      // config plugins are order sensitive
      './config/base',
      './config/css',
      './config/prod',
      './config/app'
    ].map(idToPlugin)

    if (inlinePlugins) {
      plugins = useBuiltIn !== false
        ? builtInPlugins.concat(inlinePlugins)
        : inlinePlugins
    } else {
      const projectPlugins = Object.keys(this.pkg.devDependencies || {})
        .concat(Object.keys(this.pkg.dependencies || {}))
        .filter(isPlugin)
        .map(id => {
          if (
            this.pkg.optionalDependencies &&
            id in this.pkg.optionalDependencies
          ) {
            let apply = () => {}
            try {
              apply = require(id)
            } catch (e) {
              warn(`Optional dependency ${id} is not installed.`)
            }

            return { id, apply }
          } else {
            return idToPlugin(id)
          }
        })
      plugins = builtInPlugins.concat(projectPlugins)
    }

    // Local plugins
    if (this.pkg.vuePlugins && this.pkg.vuePlugins.service) {
      const files = this.pkg.vuePlugins.service
      if (!Array.isArray(files)) {
        throw new Error(`Invalid type for option 'vuePlugins.service', expected 'array' but got ${typeof files}.`)
      }
      plugins = plugins.concat(files.map(file => ({
        id: `local:${file}`,
        apply: loadModule(`./${file}`, this.pkgContext)
      })))
    }

    return plugins
  }

  async run (name, args = {}, rawArgv = []) {
    // resolve mode
    // prioritize inline --mode
    // fallback to resolved default modes from plugins or development if --watch is defined
    const mode = args.mode || (name === 'build' && args.watch ? 'development' : this.modes[name])

    // --skip-plugins arg may have plugins that should be skipped during init()
    this.setPluginsToSkip(args)

    // load env variables, load user config, apply plugins
    this.init(mode)

    args._ = args._ || []
    let command = this.commands[name]
    if (!command && name) {
      error(`command "${name}" does not exist.`)
      process.exit(1)
    }
    if (!command || args.help || args.h) {
      command = this.commands.help
    } else {
      args._.shift() // remove command itself
      rawArgv.shift()
    }
    const { fn } = command
    return fn(args, rawArgv)
  }

  resolveChainableWebpackConfig () {
    const chainableConfig = new Config()
    // apply chains
    this.webpackChainFns.forEach(fn => fn(chainableConfig))
    return chainableConfig
  }

  resolveWebpackConfig (chainableConfig = this.resolveChainableWebpackConfig()) {
    if (!this.initialized) {
      throw new Error('Service must call init() before calling resolveWebpackConfig().')
    }
    // get raw config
    let config = chainableConfig.toConfig()
    const original = config
    // apply raw config fns
    this.webpackRawConfigFns.forEach(fn => {
      if (typeof fn === 'function') {
        // function with optional return value
        const res = fn(config)
        if (res) config = merge(config, res)
      } else if (fn) {
        // merge literal values
        config = merge(config, fn)
      }
    })

    // #2206 If config is merged by merge-webpack, it discards the __ruleNames
    // information injected by webpack-chain. Restore the info so that
    // vue inspect works properly.
    if (config !== original) {
      cloneRuleNames(
        config.module && config.module.rules,
        original.module && original.module.rules
      )
    }

    // check if the user has manually mutated output.publicPath
    const target = process.env.VUE_CLI_BUILD_TARGET
    if (
      !process.env.VUE_CLI_TEST &&
      (target && target !== 'app') &&
      config.output.publicPath !== this.projectOptions.publicPath
    ) {
      throw new Error(
        `Do not modify webpack output.publicPath directly. ` +
        `Use the "publicPath" option in vue.config.js instead.`
      )
    }

    if (typeof config.entry !== 'function') {
      let entryFiles
      if (typeof config.entry === 'string') {
        entryFiles = [config.entry]
      } else if (Array.isArray(config.entry)) {
        entryFiles = config.entry
      } else {
        entryFiles = Object.values(config.entry || []).reduce((allEntries, curr) => {
          return allEntries.concat(curr)
        }, [])
      }

      entryFiles = entryFiles.map(file => path.resolve(this.context, file))
      process.env.VUE_CLI_ENTRY_FILES = JSON.stringify(entryFiles)
    }

    return config
  }

  loadUserOptions () {
    // vue.config.js
    let fileConfig, pkgConfig, resolved, resolvedFrom
    const configPath = (
      process.env.VUE_CLI_SERVICE_CONFIG_PATH ||
      path.resolve(this.context, 'vue.config.js')
    )
    if (fs.existsSync(configPath)) {
      try {
        fileConfig = require(configPath)

        if (typeof fileConfig === 'function') {
          fileConfig = fileConfig()
        }

        if (!fileConfig || typeof fileConfig !== 'object') {
          error(
            `Error loading ${chalk.bold('vue.config.js')}: should export an object or a function that returns object.`
          )
          fileConfig = null
        }
      } catch (e) {
        error(`Error loading ${chalk.bold('vue.config.js')}:`)
        throw e
      }
    }

    // package.vue
    pkgConfig = this.pkg.vue
    if (pkgConfig && typeof pkgConfig !== 'object') {
      error(
        `Error loading vue-cli config in ${chalk.bold(`package.json`)}: ` +
        `the "vue" field should be an object.`
      )
      pkgConfig = null
    }

    if (fileConfig) {
      if (pkgConfig) {
        warn(
          `"vue" field in package.json ignored ` +
          `due to presence of ${chalk.bold('vue.config.js')}.`
        )
        warn(
          `You should migrate it into ${chalk.bold('vue.config.js')} ` +
          `and remove it from package.json.`
        )
      }
      resolved = fileConfig
      resolvedFrom = 'vue.config.js'
    } else if (pkgConfig) {
      resolved = pkgConfig
      resolvedFrom = '"vue" field in package.json'
    } else {
      resolved = this.inlineOptions || {}
      resolvedFrom = 'inline options'
    }

    if (resolved.css && typeof resolved.css.modules !== 'undefined') {
      if (typeof resolved.css.requireModuleExtension !== 'undefined') {
        warn(
          `You have set both "css.modules" and "css.requireModuleExtension" in ${chalk.bold('vue.config.js')}, ` +
          `"css.modules" will be ignored in favor of "css.requireModuleExtension".`
        )
      } else {
        warn(
          `"css.modules" option in ${chalk.bold('vue.config.js')} ` +
          `is deprecated now, please use "css.requireModuleExtension" instead.`
        )
        resolved.css.requireModuleExtension = !resolved.css.modules
      }
    }

    // normalize some options
    ensureSlash(resolved, 'publicPath')
    if (typeof resolved.publicPath === 'string') {
      resolved.publicPath = resolved.publicPath.replace(/^\.\//, '')
    }
    removeSlash(resolved, 'outputDir')

    // validate options
    validate(resolved, msg => {
      error(
        `Invalid options in ${chalk.bold(resolvedFrom)}: ${msg}`
      )
    })

    return resolved
  }
}

function ensureSlash (config, key) {
  let val = config[key]
  if (typeof val === 'string') {
    if (!/^https?:/.test(val)) {
      val = val.replace(/^([^/.])/, '/$1')
    }
    config[key] = val.replace(/([^/])$/, '$1/')
  }
}

function removeSlash (config, key) {
  if (typeof config[key] === 'string') {
    config[key] = config[key].replace(/\/$/g, '')
  }
}

function cloneRuleNames (to, from) {
  if (!to || !from) {
    return
  }
  from.forEach((r, i) => {
    if (to[i]) {
      Object.defineProperty(to[i], '__ruleNames', {
        value: r.__ruleNames
      })
      cloneRuleNames(to[i].oneOf, r.oneOf)
    }
  })
}

這裏面纔是我們要的配置文件。

以上就是vue-cli2 和 vue-cli3 的配置已經項目目錄,如有錯誤,歡迎提出,共同學習。

個人jQuery插件庫:http://www.jq22.com/myhome; 個人github地址:https://github.com/zjp2017/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章