vue-cli2和vue-cli3的區(qū)別

前言:

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

Vue2.0:

一.安裝node.js環(huán)境:

去node官網(wǎng)下載node.js并安裝(http://nodejs.cn/download/)。安裝完成后可以在終端執(zhí)行 node -v查看node 是否安裝成功,下圖是安裝成功的提示,顯示出當(dāng)前安裝的node的版本號(hào)。

image.png

二.全局安裝webpack:

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

image.png

三.全局安裝 vue-cli2:

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

image.png

四.初始化項(xiàng)目:
進(jìn)入到自己要安裝項(xiàng)目的文件夾目錄,我這里是 “D:\webpackProject\vue-cli2> ” 執(zhí)行 “vue init webpack vue-cli2-project ” 命令,出現(xiàn)如下圖提示 ,“vue-cli2-project” 是我們的項(xiàng)目文件夾的名字,就是最終顯示在index.html中的title標(biāo)簽里和package.json中的,也可以自己進(jìn)行修改,我們一般不會(huì)去改,直接按回車鍵進(jìn)行下一步。

image.png

image.png

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


image.png

這里是作者的信息,我們使用默認(rèn)的,直接下一步,


image.png

這里有兩個(gè)選項(xiàng):Runtime + Compiler 和Runtime-only ,Runtime-only要比Runtime + Compiler 輕大約6KB,而且效率要高, 按上下鍵可以進(jìn)行選擇,默認(rèn)是第一個(gè),選擇好后按回車鍵進(jìn)行下一步, 


image.png

這一步是詢問是否使用vue-router(路由),因?yàn)樵陧?xiàng)目中我們會(huì)用到所以這里按Y 鍵,進(jìn)行下一步,


image.png

這一步是詢問是否使用ESLint(語法檢查器),ES (ecscript) 即 javascript ,lint 限制的意思,也就是 javascript語法限制器,使得你的語法更加規(guī)范,如果你的語法不規(guī)范編輯器就會(huì)報(bào)錯(cuò),你可能在開發(fā)過程中因?yàn)橐粋€(gè)空格導(dǎo)致語法不規(guī)范進(jìn)而報(bào)錯(cuò)(其實(shí)你的代碼沒有問題的),所以對(duì)于初學(xué)者不建議使用此語法,所以我們選擇 n,并進(jìn)行下一步操作,

這一步是詢問是否使用單元測(cè)試,這個(gè)用的人比較少,所以我們不適用,輸入n并進(jìn)行一下步,

這一步詢問是否要進(jìn)行e2e(端到端測(cè)試),是一個(gè)自動(dòng)化測(cè)試的框架,這里我們就不使用了,直接輸入n,進(jìn)行下一步:

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

執(zhí)行 cd vue-cli2-project 進(jìn)入到我們的項(xiàng)目目錄下,然后執(zhí)行 npm run dev 命令進(jìn)行啟動(dòng)我們的項(xiàng)目,下圖是我們的項(xiàng)目目錄:
[圖片上傳失敗...(image-8ccfe-1599016807425)]

五、 項(xiàng)目目錄介紹:
1、build 文件夾:webpack的一些相關(guān)配置;
2、config 文件夾:項(xiàng)目開發(fā)環(huán)境和生產(chǎn)環(huán)境的一些相關(guān)配置;
3、node_modules 文件夾 :這里存放的是安裝包,比如webpack、第三方插件庫、項(xiàng)目的依賴文件;
4、src 文件夾:我們將要寫的代碼放在這里面,打包上線時(shí)會(huì)進(jìn)行編譯、壓縮等操作。
5、static 文件夾:這里存放的是一些靜態(tài)文件比如圖片、css文件、不需要進(jìn)行壓縮的js文件,打包時(shí)這個(gè)文件夾將原封不動(dòng)的放到dist(打包時(shí)自動(dòng)生產(chǎn)的文件夾)文件夾下面。
6、.babelrc 文件:ES6語法編譯配置,主要是將ES 轉(zhuǎn)成ES 需要適配那些瀏覽器
7、.editorconfig 文件:定義代碼格式,對(duì)代碼的風(fēng)格進(jìn)行一個(gè)統(tǒng)一。
8、.gitignore 文件:git上傳需要忽略的文件格式
9、 .postcssrc.js 文件:postcss配置文件
10、 index.html 文件:要進(jìn)行訪問的首頁面
11、package-lock.json 文件:鎖定依賴模塊和子模塊的版本號(hào)
12、package.json 文件:項(xiàng)目基本信息,包依賴信息等
13、README.md 文件:項(xiàng)目說明文件

文件詳解:
1、package.json 文件:當(dāng)我們?cè)诿钚袝r(shí) npm run dev 的時(shí)候程序執(zhí)行的是package.json文件的“script”腳本里的“dev”命令;
[圖片上傳失敗...(image-a1a0d6-1599016807425)]

這段代碼的意思是啟動(dòng) “webpack-dev-server” 服務(wù)器,“–inline” 是 重新加載改變的部分,不會(huì)刷新頁面,–progress是啟動(dòng)項(xiàng)目時(shí)顯示進(jìn)度,“–config build/webpack.dev.conf.js” 是執(zhí)行build下面的webpack.dev.conf.js配置文件。我們可以添加其他屬性比如 “–open” 是啟動(dòng)項(xiàng)目后自動(dòng)在瀏覽器打開項(xiàng)目,其它配置可以查看相關(guān)文檔(https://www.webpackjs.com/configuration/dev-server/#devserver)?!皊tart” 和“dev”的作用是一樣的,“build” 的作用是執(zhí)行 build下的build.js文件,將當(dāng)前的項(xiàng)目進(jìn)行打包。打包后生成一個(gè)dist文件夾,放在其里面。webpack.dev.conf.js文件是我們?cè)陂_發(fā)環(huán)境下的webpack配置文件,打開次文件,內(nèi)容如下:
[圖片上傳失敗...(image-8405a5-1599016807425)]

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模塊,對(duì)路徑進(jìn)行處理
const baseWebpackConfig = require('./webpack.base.conf') //將生產(chǎn)和開發(fā)環(huán)境下共用的配置文件進(jìn)行了抽離形成了改文件
const CopyWebpackPlugin = require('copy-webpack-plugin') //拷貝插件
const HtmlWebpackPlugin = require('html-webpack-plugin')  //加載html模塊
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') //友好的錯(cuò)誤提示插件
const portfinder = require('portfinder')   //在當(dāng)前機(jī)器上找一個(gè)可打開的端口號(hào),默認(rèn)是8080,如果端口號(hào)被占用則重新尋找可打開的端口號(hào)。

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

const devWebpackConfig = merge(baseWebpackConfig, {   //利用merge插件將 baseWebpackConfig 配置與當(dāng)前配置進(jìn)行合并
  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',      //當(dāng)使用inline mode,devTools的命令行中將會(huì)顯示一些調(diào)試信息
    historyApiFallback: {           //當(dāng)使用 HTML5 History API 時(shí),任意的 404 響應(yīng)都可能需要被替代為 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”命令中進(jìn)行配置
    port: PORT || config.dev.port,   //要開啟的端口號(hào),可在package.json中的“dev”命令中進(jìn)行配置
    open: config.dev.autoOpenBrowser,//是否自動(dòng)在瀏覽器中打開,可在package.json中的“dev”命令中進(jìn)行配置
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath, //
    proxy: config.dev.proxyTable,   //當(dāng)出現(xiàn)跨域時(shí)設(shè)置代理,這里引入了config下的index.js的配置
    quiet: true, // necessary for FriendlyErrorsPlugin  啟用 quiet 后,除了初始啟動(dòng)信息之外的任何內(nèi)容都不會(huì)被打印到控制臺(tái)。這也意味著來自 webpack 的錯(cuò)誤或警告在控制臺(tái)不可見
    watchOptions: {
      poll: config.dev.poll,
    }
  },
  plugins: [ //插件部分
    new webpack.DefinePlugin({   //配置全局變量
      'process.env': require('../config/dev.env')  
    }),
    new webpack.HotModuleReplacementPlugin(),     // 模塊熱替換它允許在運(yùn)行時(shí)更新各種模塊,而無需進(jìn)行完全刷新
    new webpack.NamedModulesPlugin(),            //  HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),          // 這個(gè)插件的作用是在熱加載時(shí)直接返回更新文件名,而不是文件的id。
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({   //打包時(shí)生成index.html并且自動(dòng)加載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整個(gè)文件夾原封不動(dòng)地拷貝到dist目錄下。
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port  //獲取當(dāng)前的端口號(hào)
  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的配置(公共配置)與本文件配置進(jìn)行合并,再看一下 webpack.base.conf.js 文件:
3、build/webpack.base.conf.js 文件

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

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

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

    rules: [
      // 配置各種loader,來處理對(duì)應(yīng)的文件
      {
        test: /\.vue$/,   //使用vue-loader處理以.vue結(jié)束的文件
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,    //使用babel-loader處理以.js結(jié)束的文件,即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同級(jí)目錄下的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'
  }
}

主要的說明已經(jīng)注釋在了文件中,這個(gè)問價(jià)的主要配置有entry(入口文件)、output(輸出文件)、loader ,這些都是必備的,而一些plugins(插件)已經(jīng)在對(duì)應(yīng)的環(huán)境文件(webpack.dev.config.js、webpack.prod.config.js)中進(jìn)行了配置,再看一下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中引起頁面樣式加載錯(cuò)亂的現(xiàn)象
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')//主要是用來壓縮css文件
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')  //對(duì)js文件進(jìn)行壓縮

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: {  //配置項(xiàng)
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,  //使用sourceMap將錯(cuò)誤消息位置映射到模塊(這會(huì)減慢編譯速度)。
      parallel: true        //啟用/禁用多進(jìn)程并行運(yùn)行,啟用后會(huì)提高構(gòu)建速度
    }),

    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 } }  //判斷是否生成內(nèi)聯(lián)映射,如果生成則會(huì)生成一個(gè)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, //將會(huì)生成一個(gè)index.html文件,放到dist文件下
      template: 'index.html',
      inject: true,                //將所有js資源放在body標(biāo)簽的底部
      minify: {                   //控制是否進(jìn)行壓縮
        removeComments: true,     //刪除所有的注釋
        collapseWhitespace: true, //折疊構(gòu)成文檔樹中文本節(jié)點(diǎn)的空白
        removeAttributeQuotes: true //盡可能刪除屬性周圍的引號(hào)
        // 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(), //該插件會(huì)根據(jù)模塊的相對(duì)路徑生成一個(gè)四位數(shù)的hash作為模塊id, 建議用于生產(chǎn)環(huán)境。
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),//啟用作用域提升,讓代碼文件更小、運(yùn)行的更快
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({ //主要是用來提取第三方庫和公共模塊,避免首屏加載的bundle文件或者按需加載的bundle文件體積過大,從而導(dǎo)致加載時(shí)間過長(zhǎng)
      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([  //復(fù)制模塊
      {
        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

當(dāng)我們執(zhí)行 npm run build 打包時(shí)執(zhí)行的是: build下的build.js文件,build.js中引入webpack.prod.config.js,因此build.js才是生產(chǎn)環(huán)境所需的webpack文件。
[圖片上傳失敗...(image-6dbc38-1599016807423)]

5、build/build.js:

'use strict'
require('./check-versions')() //該文件用于檢測(cè)node和npm的版本,實(shí)現(xiàn)版本依賴

process.env.NODE_ENV = 'production'

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

const spinner = ora('building for production...') //設(shè)置一個(gè)動(dòng)畫的內(nèi)容為 "building for production..."
spinner.start()   //加載動(dòng)畫

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {  //利用 rm 模塊先刪除dist文件再生成新文件,因?yàn)橛袝r(shí)候會(huì)使用hash來命名,刪除整個(gè)文件可避免冗余
  if (err) throw err
  webpack(webpackConfig, (err, stats) => {   //將一下配置內(nèi)容與 webpack.prod.conf.js中的配置進(jìn)行合并
    spinner.stop()  //停止動(dòng)畫
    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: 檢測(cè)node和npm的版本,實(shí)現(xiàn)版本依賴

'use strict'
// 該文件用于檢測(cè)node和npm的版本,實(shí)現(xiàn)版本依賴
const chalk = require('chalk')  //node.js中的模塊,作用是修改控制臺(tái)中字符串的樣式
const semver = require('semver')  //node.js中的模塊,對(duì)版本進(jìn)行檢查
const packageConfig = require('../package.json') //引入page.json文件
const shell = require('shelljs')

function exec (cmd) {
  //通過child_process模塊的新建子進(jìn)程,執(zhí)行 Unix 系統(tǒng)命令后轉(zhuǎn)成沒有空格的字符串
  return require('child_process').execSync(cmd).toString().trim()
}

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

if (shell.which('npm')) {
  versionRequirements.push({
    name: 'npm',
    currentVersion: exec('npm --version'),   //自動(dòng)調(diào)用npm --version命令,并且把參數(shù)返回給exec函數(shù),從而獲取純凈的版本號(hào)
    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)) {
      //如果上面的版本號(hào)不符合package.json文件中指定的版本號(hào),就執(zhí)行下面錯(cuò)誤提示的代碼
      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'

//根據(jù)NODE_ENV這個(gè)變量分析是否是生產(chǎn)環(huán)境,然后根據(jù)不同的環(huán)境來加載,判斷是否開啟了sourceMap的功能。方便之后在cssLoaders中加上sourceMap功能。然后判斷是否設(shè)置了cacheBusting屬性,
// 它指的是緩存破壞,特別是進(jìn)行sourceMap debug時(shí),設(shè)置成false是非常有幫助的。最后就是一個(gè)轉(zhuǎn)化請(qǐng)求的內(nèi)容,video、source、img、image等的屬性進(jìn)行配置。具體的還是需要去了解vue-loader這個(gè)
// 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
//處理項(xiàng)目中的css文件,生產(chǎn)環(huán)境和測(cè)試環(huán)境默認(rèn)是打開sourceMap,而extract中的提取樣式到單獨(dú)文件只有在生產(chǎn)環(huán)境中才需要
module.exports = {
  loaders: utils.cssLoaders({
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled, 
  cacheBusting: config.dev.cacheBusting,
  transformToRequire: {//在模版編譯過程中,編譯器可以將某些屬性,如 src 路徑,轉(zhuǎn)換為require調(diào)用,以便目標(biāo)資源可以由 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中引起頁面樣式加載錯(cuò)亂的現(xiàn)象
const packageConfig = require('../package.json')

//導(dǎo)出文件的位置,根據(jù)環(huán)境判斷開發(fā)環(huán)境和生產(chǎn)環(huán)境,為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) {   //導(dǎo)出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] //根據(jù)傳入的參數(shù)判斷是使用cssLoader、 postcssLoader還是只使用 cssLoader

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {  //將后面的兩個(gè)對(duì)象合并后再進(jìn)行復(fù)制
          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: 生產(chǎn) 和 開發(fā) 環(huán)境下webpack的公共配置文件

const path = require('path')

module.exports = {
  dev: {  //開發(fā)環(huán)境下的配置

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

    // Various Dev Server settings
    host: 'localhost', // 域名
    port: 8080, // 開啟的端口號(hào),默認(rèn)是8080
    autoOpenBrowser: true, //是否自動(dòng)打開瀏覽器
    errorOverlay: true,  //瀏覽器錯(cuò)誤提示
    notifyOnErrors: true, //跨平臺(tái)錯(cuò)誤提示
    poll: false, // 使用文件系統(tǒng)(file system)獲取文件改動(dòng)的通知devServer.watchOptions

    /**
     * Source Maps
     */

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

    cacheBusting: true,//使緩存失效

    cssSourceMap: true   //代碼壓縮后進(jìn)行調(diào)bug定位將非常困難,于是引入sourcemap記錄壓縮前后的位置信息記錄,當(dāng)產(chǎn)生錯(cuò)誤時(shí)直接定位到未壓縮前的位置,將大大的方便我們調(diào)試
  },

  build: { //生產(chǎn)發(fā)環(huán)境下的配置
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'), //index.html編譯后生成的位置和名字

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),//編譯后存放生成環(huán)境代碼的位置
    assetsSubDirectory: 'static',  //js,css,images存放文件夾名
    assetsPublicPath: '/',  //發(fā)布的根目錄,通常本地打包dist后打開文件會(huì)報(bào)錯(cuò),此處修改為./。如果是上線的文件,可根據(jù)文件存放位置進(jìn)行更改路徑

    productionSourceMap: true,

    devtool: '#source-map',

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

    bundleAnalyzerReport: process.env.npm_config_report
  }
}

10、config/dev.env.js:

'use strict'
// 當(dāng)在開發(fā)環(huán)境下引用(webpack.dev.config.js中的plugin中)的是此文件,次文件指定了 開發(fā)模式: node-env ,
//利用merge方法將prod.env.js與本文件進(jìn)行合并,在開發(fā)模式下輸出 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'
// 在生產(chǎn)模式下調(diào)用此文件
// 在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文件夾: 該文件夾下面存放的是我們項(xiàng)目代碼以及一些文件,components文件夾存放了我們自己寫的組件,router文件夾里面存放了路由配置,mian.js是整個(gè)項(xiàng)目的入口js,在build文件夾下的webpack.dev.config.js中的entry中有配置(

app: ‘./src/main.js’)。App.vue文件是項(xiàng)目的首頁面。

vue 3.0:

1.安裝vue3:新建一個(gè)文件夾,進(jìn)入該文件夾下,執(zhí)行 vue create ( 項(xiàng)目名稱) , 如下圖:


image.png

vuecli3為項(xiàng)目名稱,進(jìn)入下一步,


image.png

上面提示:請(qǐng)選擇一個(gè)配置。下面有3個(gè)選項(xiàng),第一個(gè) “myset ” 是 我自己手動(dòng)選擇的配置,你們第一個(gè)安裝你沒有這個(gè)選項(xiàng),如果選擇了第3個(gè)通過手動(dòng)選擇后,下次再安裝時(shí)會(huì)出現(xiàn)在這里,第二個(gè) “default”是默認(rèn)的,第3個(gè)是 手動(dòng)選擇。我們先選擇第3個(gè),進(jìn)入下一步,


image.png

這里要我們選擇一個(gè)配置,按住上下鍵進(jìn)行調(diào)轉(zhuǎn),空格鍵進(jìn)行選中或者取消,

這一步詢問的是 把項(xiàng)目的配置文件放在獨(dú)立的配置文件中還是放在package.json文件中,這里我們選擇第一個(gè),方便我們以后的修改,進(jìn)行下一步


image.png

這里詢問的是我們手動(dòng)配置要不要進(jìn)行保存,以便下次使用,也就是安裝第一步的時(shí)候的選擇,輸入 y,


image.png

這里要輸入的是要保存的命字,進(jìn)行一下步安裝,


image.png

安裝完成。
啟動(dòng)項(xiàng)目:


image.png

這是vue3的項(xiàng)目結(jié)構(gòu),顯然和vue2的結(jié)構(gòu)不一樣,沒有了config文件夾而且還多了一個(gè).git文件,方便我們項(xiàng)目管理,其中public相當(dāng)于vue2中的static靜態(tài)文件夾,相同文件我就不說了,我只說一下不同文件。

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

開發(fā)依賴少了很多,因?yàn)関ue3.0講究的是 0 配置,因?yàn)椴伙@示的這些文件不需要我們?nèi)ジ模覀兺ㄟ^npm安裝的依賴會(huì)存在哪里呢?

  
image.png

這里我安裝了2個(gè)依賴,很顯然是放在package.json文件下的,方便我們?nèi)ス芾碜约旱囊蕾?。那默認(rèn)的那些依賴存在哪里呢?
。其實(shí)是通過 “@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中有這一行代碼:


image.png

所以再找到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代理配置詳解請(qǐng)看上一篇文章,如果對(duì)你有用請(qǐng)點(diǎn)波關(guān)注。
文章出處:https://blog.csdn.net/vmei_2019/article/details/102799987

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容