在本身的電腦下載了npm 與 node的狀況下 可以使用vue-cli快速構建vue項目執行命令以下:javascript
# 全局安裝 vue-cli
$ npm install -g vue-cli
# 建立一個基於 "webpack" 模板的新項目
$ vue init webpack my-project
# 安裝依賴,走你
$ cd my-project
$ npm install
$ npm run dev
// 這個vuetest是你的項目名稱 本身起個名字就行了
// 以後就能夠按照頁面提示 一直輸入enter鍵便可
我本身在安裝的時候 報了一個關於chromedriver版本錯誤的問題 可使用如下命令來解決css
// 這個緣由是package.json 裏面引入的chromedriver 版本與本身電腦裏下載的版本是不同的所致使 npm install chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver // 或者是: npm install chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver // 運行結束以後 就能夠直接使用 npm run 啓動項目
下面來看一下項目結構吧html
簡單來介紹一下這個目錄vue
bulid 構建服務和webpack配置 下面會有各個文件的詳細介紹java
config 構建項目的不一樣環境的配置 包括打包路徑的配置 環境的聲明 好比 生產環境 開發環境 測試環境。node
src 項目目錄webpack
在開發環境下,咱們首先考慮的是方便開發,方便代碼調試,不須要考慮代碼合併和css樣式分離這些。git
這裏主要說三個 :1.css模塊化;2.模塊熱替換功能;3.source-map(代碼映射)github
首先須要知道的是,webpack的配置是經過module.exports導出一個node環境下全局的對象。而後這樣再去就能更方便了解webpack 的寫法。web
主要代碼在於:
const devWebpackConfig = merge(baseWebpackConfig, {} //這個是將baseWebpackConfi與該文件裏的配置進行結合。具體能夠查看下merge的用法,也就是說 若是你想了解一些基本的配置,應該這時候去看下webpack.base.conf.js文件。
2:webpack.base.conf.js
先看代碼註釋
在這個文件裏 配置了一些好比入口文件,打包與運行的文件路徑,固然 這裏都是在用變量去表示,最明顯的栗子能夠從
首先解釋一下:process這個對象提供一系列屬性,用於返回系統信息。
process.env:指向當前shell的環境變量,好比process.env.HOME 在我電腦裏返回的是C:\User\dell
process模塊用來與當前進程互動,能夠經過全局變量process訪問,沒必要使用require命令加載。它是一個EventEmitter對象的實例。上面有不少的信息。
這裏看出來,在dev.conf.js文件裏 有進行判斷是生產仍是開發環境的判斷,也許會有疑問,咱們在代碼裏 怎麼知道當前運行的是開發環境 仍是生產環境呢,並無直接去指明當前欲運行的環境。其實這個是在咱們運行好比 npm run dev 或者 npm build 時 在運行命令上就已經帶上了參數,指定了當前要運行的環境。這裏也就再也不進行細說。
3:webpack.prod.conf.js
當咱們運行打包 npm run build命令時 運行的是build/build.js文件,能夠看到該文件引入的是webpack.prod.conf.js另外在build.js文件里加了幾個判斷 還有刪除打包文件的命令。
相比開發環境,生產環境打包是要最後發佈到服務器部署的代碼,咱們須要儘可能保持代碼簡潔,加載性能最優,不須要調試輔助工具。
咱們從這幾個方面優化 :1.公共模塊拆分,單獨打包;2. css文件分離,單獨打包輸出;3.代碼壓縮;
'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') //幫作咱們配置html文件中js文件的引入的 // css單獨打包插件 const ExtractTextPlugin = require('extract-text-webpack-plugin') const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') // 壓縮工具 const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const env = process.env.NODE_ENV === 'testing' ? require('../config/test.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, parallel: true }), // extract css into its own file new ExtractTextPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css'), // Setting the following option to `false` will not extract CSS from codesplit chunks. // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack. // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110 allChunks: true, }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: config.build.productionSourceMap ? { safe: true, map: { inline: false } } : { safe: true } }), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin 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' }), // keep module.id stable when vendor modules does not change new webpack.HashedModuleIdsPlugin(), // enable scope hoisting new webpack.optimize.ModuleConcatenationPlugin(), // split vendor js into its own file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks (module) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity }), // This instance extracts shared chunks from code splitted chunks and bundles them // in a separate chunk, similar to the vendor chunk // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk new webpack.optimize.CommonsChunkPlugin({ name: 'app', async: 'vendor-async', children: true, minChunks: 3 }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ] }) if (config.build.productionGzip) { const CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) ) } if (config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig
經常使用的一些配置更改:看註釋也就能看懂了
在config文件下的index.js文件
'use strict' // Template version: 1.3.1 // see http://vuejs-templates.github.io/webpack for documentation. // path是node.js的路徑模塊,用來處理路徑統一的問題 const path = require('path') module.exports = { dev: { // Paths assetsSubDirectory: 'static', // 編譯輸出的二級目錄 assetsPublicPath: '/', // 編譯發佈的根目錄,可配置爲資源服務器域名或 CDN 域名 // 下面是代理表,做用是用來,建一個虛擬api服務器用來代理本機的請求,只能用於開發模式 proxyTable: { // '/api': { // target: 'http://localhost:8082', // pathRewrite: { // '^/api': '/' // } // }, // '/pop-shared-web-components': { // target: 'http://pop-shared-web-components.cn:3000', // pathRewrite: { // '^/pop-shared-web-components': '/' // } // } }, //下面是proxyTable的通常用法 //vue-cli使用這個功能是藉助http-proxy-middleware插件,通常解決跨域請求api // proxyTable: { // '/list': { // target: 'http://api.xxxxxxxx.com', -> 目標url地址 // changeOrigin: true, -> 指示是否跨域 // pathRewrite: { // '^/list': '/list' -> 可使用 /list 等價於 api.xxxxxxxx.com/list // } // } // } // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined // 運行測試頁面的端口 autoOpenBrowser: true, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, cssSourceMap: true }, // 下面是build也就是生產編譯環境下的一些配置 build: { // Template for index.html //path.resolve() 方法會把一個路徑或路徑片斷的序列解析爲一個絕對路徑。 index: path.resolve(__dirname, '../dist/index.html'), // 編譯輸入的 index.html 文件 // Paths assetsRoot: path.resolve(__dirname, '../dist'), // 編譯輸出的靜態資源路徑 是靜態資源的根目錄 也就是dist目錄 assetsSubDirectory: 'static', // 編譯輸出的二級目錄 assetsPublicPath: '/', // 編譯發佈的根目錄,可配置爲資源服務器域名或 CDN 域名 /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // 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 // 下面是是否在生產環境中壓縮代碼,若是要壓縮必須安裝compression-webpack-plugin productionGzip: false, // 下面定義要壓縮哪些類型的文件 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 // 下面是用來開啓編譯完成後的報告,能夠經過設置值爲true和false來開啓或關閉 // 下面的process.env.npm_config_report表示定義的一個npm_config_report環境變量,能夠自行設置 bundleAnalyzerReport: process.env.npm_config_report } }
以上算是對各個文件作了簡單的介紹