vue-cli是vue提供構建單頁應用的腳手架。它可以幫助開發者快速的建立vue項目。這篇文章主要介紹如何使用vue-cli,以及它建立的vue項目結構。還有就是對於build目錄下的配置文件進行一些梳理總結。css
安裝vue-cli十分簡單,執行下面的命令便可html
npm install -g vue-cli
以後能夠經過vue list
來查看可使用哪些模板
vue
經過vue-cli建立一個vue項目node
vue init webpack <your project>
以後進入你的項目webpack
cd <your project>
經過npm安裝依賴git
npm install
啓動項目github
npm run dev
以後咱們就看到項目啓動了
web
打包項目vue-cli
npm run build
├── build --------------------------------- webpack相關配置文件 │ ├── build.js --------------------------webpack打包配置文件 │ ├── check-versions.js ------------------------------ 檢查npm,nodejs版本 │ ├── dev-client.js ---------------------------------- 設置環境 │ ├── dev-server.js ---------------------------------- 建立express服務器,配置中間件,啓動可熱重載的服務器,用於開發項目 │ ├── utils.js --------------------------------------- 配置資源路徑,配置css加載器 │ ├── vue-loader.conf.js ----------------------------- 配置css加載器等 │ ├── webpack.base.conf.js --------------------------- webpack基本配置 │ ├── webpack.dev.conf.js ---------------------------- 用於開發的webpack設置 │ ├── webpack.prod.conf.js --------------------------- 用於打包的webpack設置 ├── config ---------------------------------- 配置文件 ├── node_modules ---------------------------- 存放依賴的目錄 ├── src ------------------------------------- 源碼 │ ├── assets ------------------------------ 靜態文件 │ ├── components -------------------------- 組件 │ ├── main.js ----------------------------- 主js │ ├── App.vue ----------------------------- 項目入口組件 │ ├── router ------------------------------ 路由 ├── package.json ---------------------------- node配置文件 ├── .babelrc--------------------------------- babel配置文件 ├── .editorconfig---------------------------- 編輯器配置 ├── .gitignore------------------------------- 配置git可忽略的文件
首選來看一下package.json
裏面scripts
字段,看一下在執行npm run dev
和npm run build
時作了什麼express
"name": "wheelsfactory", "version": "1.0.0", "description": "輪子工廠--一個分享優秀的vue,angular組件的網站 http://www.wheelsfactory.cn", "scripts": { "dev": "node build/dev-server.js", "start": "node build/dev-server.js", "build": "node build/build.js" }
當咱們執行npm run dev
時,首選執行的是dev-server.js
當咱們執行npm run build
時,首選執行的是build.js
require('./check-versions')() //引入相關配置 var config = require('../config') // 檢查Node的環境變量,若是沒有則使用配置文件中設置的環境 if (!process.env.NODE_ENV) { process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) } //opn -- A better node-open. Opens stuff like websites, files, executables. Cross-platform. //這裏用來打開默認瀏覽器,打開dev-server監聽的端口 var opn = require('opn') var path = require('path') var express = require('express') var webpack = require('webpack') //express中間件,用於http請求代理到其餘服務器 var proxyMiddleware = require('http-proxy-middleware') //判斷當前環境,選擇導入的webpack配置 var webpackConfig = process.env.NODE_ENV === 'testing' ? require('./webpack.prod.conf') : require('./webpack.dev.conf') // default port where dev server listens for incoming traffic //默認的dev-server的監聽端口 var port = process.env.PORT || config.dev.port // automatically open browser, if not set will be false //是否自動打開瀏覽器,默認是false var autoOpenBrowser = !!config.dev.autoOpenBrowser // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware //定義http代理到你的自定義的API後端 var proxyTable = config.dev.proxyTable //建立express實例 var app = express() // 根據webpack的config建立Compiler對象 var compiler = webpack(webpackConfig) //使用compiler相應的文件進行編譯和綁定,編譯後的內容將存放在內存中 var devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: true }) //用於實現熱重載 var hotMiddleware = require('webpack-hot-middleware')(compiler, { log: false, heartbeat: 2000 }) // force page reload when html-webpack-plugin template changes //當html-webpack-plugin提交頁面以後,使用熱重載強制頁面重載 compiler.plugin('compilation', function (compilation) { compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() }) }) // proxy api requests //在express上使用代理表中的配置 Object.keys(proxyTable).forEach(function (context) { var options = proxyTable[context] if (typeof options === 'string') { options = { target: options } } app.use(proxyMiddleware(options.filter || context, options)) }) // handle fallback for HTML5 history API //一個解決單頁的重定向錯誤的插件 app.use(require('connect-history-api-fallback')()) // serve webpack bundle output // 使用devMiddleware,webpack編譯後的文件將掛到express服務器上 app.use(devMiddleware) // enable hot-reload and state-preserving // compilation error display // 使用熱重載中間件 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')) //設置應用的url var uri = 'http://localhost:' + port var _resolve var readyPromise = new Promise(resolve => { _resolve = resolve }) console.log('> Starting dev server...') //devMiddleware valid以後,啓動服務 devMiddleware.waitUntilValid(() => { console.log('> Listening at ' + uri + '\n') // when env is testing, don't need open it //若是設置爲自動打開瀏覽器,經過opn打開uri if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { opn(uri) } _resolve() }) //監聽配置的端口 var server = app.listen(port) module.exports = { ready: readyPromise, close: () => { server.close() } }
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' }, output: { //webpack輸出文件的路徑 path: config.build.assetsRoot, //輸出的文件命名格式 filename: '[name].js', // webpack編譯輸出的發佈路徑 publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, //模塊resolve的規則 resolve: { //resolve的後綴名 extensions: ['.js', '.vue', '.json'], //配置路徑別名,好比import Vue from 'vue/dist/vue.common.js'--> import Vue from 'vue' alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } }, //配置不一樣類型模塊的處理規則 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 { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, //全部的音頻文件使用url-loader { test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('media/[name].[hash:7].[ext]') } }, //全部的字體文件使用url-loader { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] } }
var utils = require('./utils') var webpack = require('webpack') var config = require('../config') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') //生成html文件並自動注入依賴文件的插件, script & link var HtmlWebpackPlugin = require('html-webpack-plugin') //一個輸出webpack警告,錯誤的插件 var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') // add hot-reload related code to entry chunks //添加熱重載相關的代碼到entry chunks Object.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) }) //合併webpack.base.conf module.exports = merge(baseWebpackConfig, { module: { //使用styleLoaders處理樣式文件 rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // cheap-module-eval-source-map is faster for development //配置Source Maps 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(), //在編譯出現錯誤時,使用 NoEmitOnErrorsPlugin 來跳過輸出階段。這樣能夠確保輸出資源不會包含錯誤。 new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true }), new FriendlyErrorsPlugin() ] })
** 配置Source Maps
require('./check-versions')() process.env.NODE_ENV = 'production' //控制檯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') //在控制檯輸出building for production... var spinner = ora('building for production...') //開始loading動畫 spinner.start() //獲取輸出文件路徑 rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err //webpack編譯 webpack(webpackConfig, function (err, stats) { //中止loading動畫 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' )) }) })
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 CopyWebpackPlugin = require('copy-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin') // 抽取css,js文件,與webpack輸出的bundle分離 var ExtractTextPlugin = require('extract-text-webpack-plugin') var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') var env = process.env.NODE_ENV === 'testing' ? require('../config/test.env') : config.build.env //合併webpack.base.conf var webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : 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 }), //壓縮js插件 new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: true }), // extract css into its own file //從bundle中抽取css文件 new ExtractTextPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css') }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. //壓縮抽取的css文件 new OptimizeCSSPlugin({ cssProcessorOptions: { 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 //用於生成dist/index.html,加入hash用於緩存。hash不改變不進行更新 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 //分離第三方js到單獨的文件中 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'] }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ] }) // 配置gzip模式 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 }) ) } //配置webpack-bundle-analyzer,分析打包後生成的文件結構 if (config.build.bundleAnalyzerReport) { var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig
最後是config中的index.js文件,它都配置了什麼
var path = require('path') module.exports = { //打包時使用的配置 build: { //webpack的環境 env: require('./prod.env'), //輸入的index.html的路徑 index: path.resolve(__dirname, '../dist/index.html'), //輸出的目標文件夾路徑 assetsRoot: path.resolve(__dirname, '../dist'), //輸出的子文件夾路徑 assetsSubDirectory: 'static', //發佈路徑 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'), //端口 port: 8080, //是否自動打開瀏覽器 autoOpenBrowser: true, //輸出的子文件夾路徑 assetsSubDirectory: 'static', //發佈路徑 assetsPublicPath: '/', //配置代理表 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: false } }
vue-cli給建立vue項目提供了很大的便利。可是同時大量的第三方庫的使用,會讓打包後的js變的很大,因此仍是要熟悉配置,熟悉第三方插件的使用,才能夠開發更高效的開發web應用。這裏把vue-cli的一些相關內容給本身作一個總結,便於之後查閱。也是但願對其餘開發者有幫助。有不足之處請指正。
最後推薦一下輪子工廠--一個分享優秀的vue,angular組件的網站