題言:
相信很多vue新手,都像我一樣,只是知道可以用vue-cli直接生成一個vue項目的架構,並不明白,他究竟是怎么運行的,現在我們一起來研究一下。。。
一、安裝vue-cli,相信你既然會用到vue-cli,自然node環境是OK的,直接命令行下安裝
npm install -g vue-cli
二、使用vue-cli創建vue項目
用法: vue init <template-name> <project-name>
1 template-name: 2 . webpack 3 . webpack-simple // 一個簡單webpack+vue-loader的模板,不包含其他功能。 4 . browserify // 一個全面的Browserify+vueify 的模板,功能包括熱加載,linting,單元檢測。 5 . browserify-simple // 一個簡單Browserify+vueify的模板,不包含其他功能。 6 . pwa // 基於webpack模板的vue-cli的PWA模板 7 . simple // 一個最簡單的單頁應用模板
常用的就是webpack了,模板之間的不同,自己體驗
示例:
vue init webpack my-project
執行指令后,會讓用戶輸入幾個基本的選項,如圖所示
需要注意的是項目的名稱不能大寫,不然會報錯。
- Project name :項目名稱 ,如果不需要更改直接回車就可以了。注意:這里不能使用大寫。
- Project description:項目描述,默認為A Vue.js project,直接回車,不用編寫。
- Author:作者,如果你有配置git,他會讀取.ssh文件中的user。
- Install vue-router? 是否安裝vue的路由插件,Y代表安裝,N無需安裝,下面的命令也是一樣的。
- Use ESLint to lint your code? 是否用ESLint來限制你的代碼錯誤和風格
- setup unit tests with Karma + Mocha? 是否需要安裝單元測試工具Karma+Mocha。
- Setup e2e tests with Nightwatch?是否安裝e2e來進行用戶行為模擬測試。
- Should we run npm install for you after the project has been created?(recommended)npm
詢問你使用npm安裝還是yarn安裝包依賴,我這里選擇的是npm,yarn更快更好,使用yarn之前確保你的電腦已經安裝yarn。
根據提示,待模板加載完成之后,執行下面兩條命令
cd my-project npm run dev // dev代表下圖框選的內容
出現如圖,就是編譯成功了,英文稍微好點,就能讀懂
這時候,鼠標放到 http://localhost:8080 會提示用“Alt+點擊”即可訪問;
出現如圖,就成功創建了項目;
三、文件目錄結構
本文主要分析開發(dev)和構建(build)兩個過程涉及到的文件,故下面文件結構僅列出相應的內容。
|-- build // 項目構建(webpack)相關代碼 | |-- build.js // 生產環境構建代碼 | |-- check-version.js // 檢查node、npm等版本 | |-- utils.js // 構建工具相關 | |-- vue-loader.conf.js // webpack loader配置 | |-- webpack.base.conf.js // webpack基礎配置 | |-- webpack.dev.conf.js // webpack開發環境配置,構建開發本地服務器 | |-- webpack.prod.conf.js // webpack生產環境配置 |-- config // 項目開發環境配置 | |-- dev.env.js // 開發環境變量 | |-- index.js // 項目一些配置變量 | |-- prod.env.js // 生產環境變量 | |-- test.env.js // 測試腳本的配置 |-- src // 源碼目錄 | |-- components // vue所有組件 | |-- router // vue的路由管理 | |-- App.vue // 頁面入口文件 | |-- main.js // 程序入口文件,加載各種公共組件 |-- static // 靜態文件,比如一些圖片,json數據等 |-- test // 測試文件 | |-- e2e // e2e 測試 | |-- unit // 單元測試 |-- .babelrc // ES6語法編譯配置 |-- .editorconfig // 定義代碼格式 |-- .eslintignore // eslint檢測代碼忽略的文件(夾) |-- .eslintrc.js // 定義eslint的plugins,extends,rules |-- .gitignore // git上傳需要忽略的文件格式 |-- .postcsssrc // postcss配置文件 |-- README.md // 項目說明,markdown文檔 |-- index.html // 訪問的頁面 |-- package.json // 項目基本信息,包依賴信息等
如圖所示:
下邊是具體文件的具體分析
1. package.json文件
package.json文件是項目的配置文件,定義了項目的基本信息以及項目的相關包依賴,npm運行命令等
scripts 里定義的是一些比較長的命令,用node去執行一段命令,比如
npm run dev
其實就是執行
webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
這句話的意思是利用 webpack-dev-server 讀取 webpack.dev.conf.js 信息並啟動一個本地服務器。
2. dependencies VS devDependencies
簡單的來說
dependencies 是運行時依賴(生產環境) npm install --save **(package name)
devDependencies 是開發時的依賴(開發環境) npm install --save-dev **(package name)
3. 基礎配置文件 webpack.base.conf.js
基礎的 webpack 配置文件主要根據模式定義了入口出口,以及處理 vue, babel等的各種模塊,是最為基礎的部分。其他模式的配置文件以此為基礎通過 webpack-merge 合並。
1 'use strict' 2 const path = require('path') 3 const utils = require('./utils') 4 const config = require('../config') 5 const vueLoaderConfig = require('./vue-loader.conf') 6 7 // 獲取絕對路徑 8 function resolve (dir) { 9 return path.join(__dirname, '..', dir) 10 } 11 <!-- 定義一下代碼檢測的規則 --> 12 const createLintingRule = () => ({ 13 test: /\.(js|vue)$/, 14 loader: 'eslint-loader', 15 enforce: 'pre', 16 include: [resolve('src'), resolve('test')], 17 options: { 18 formatter: require('eslint-friendly-formatter'), 19 emitWarning: !config.dev.showEslintErrorsInOverlay 20 } 21 }) 22 23 module.exports = { 24 // 基礎上下文 25 context: path.resolve(__dirname, '../'), 26 // webpack的入口文件 27 entry: { 28 app: './src/main.js' 29 }, 30 // webpack的輸出文件 31 output: { 32 path: config.build.assetsRoot, 33 filename: '[name].js', 34 publicPath: process.env.NODE_ENV === 'production' 35 ? config.build.assetsPublicPath 36 : config.dev.assetsPublicPath 37 }, 38 /** 39 * 當webpack試圖去加載模塊的時候,它默認是查找以 .js 結尾的文件的, 40 * 它並不知道 .vue 結尾的文件是什么鬼玩意兒, 41 * 所以我們要在配置文件中告訴webpack, 42 * 遇到 .vue 結尾的也要去加載, 43 * 添加 resolve 配置項,如下: 44 */ 45 resolve: { 46 extensions: ['.js', '.vue', '.json'], 47 alias: { // 創建別名 48 'vue$': 'vue/dist/vue.esm.js', 49 '@': resolve('src'), // 如 '@/components/HelloWorld' 50 } 51 }, 52 // 不同類型模塊的處理規則 就是用不同的loader處理不同的文件 53 module: { 54 rules: [ 55 ...(config.dev.useEslint ? [createLintingRule()] : []), 56 {// 對所有.vue文件使用vue-loader進行編譯 57 test: /\.vue$/, 58 loader: 'vue-loader', 59 options: vueLoaderConfig 60 }, 61 {// 對src和test文件夾下的.js文件使用babel-loader將es6+的代碼轉成es5 62 test: /\.js$/, 63 loader: 'babel-loader', 64 include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] 65 }, 66 {// 對圖片資源文件使用url-loader 67 test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 68 loader: 'url-loader', 69 options: { 70 // 小於10K的圖片轉成base64編碼的dataURL字符串寫到代碼中 71 limit: 10000, 72 // 其他的圖片轉移到靜態資源文件夾 73 name: utils.assetsPath('img/[name].[hash:7].[ext]') 74 } 75 }, 76 {// 對多媒體資源文件使用url-loader 77 test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 78 loader: 'url-loader', 79 options: { 80 // 小於10K的資源轉成base64編碼的dataURL字符串寫到代碼中 81 limit: 10000, 82 // 其他的資源轉移到靜態資源文件夾 83 name: utils.assetsPath('media/[name].[hash:7].[ext]') 84 } 85 }, 86 {// 對字體資源文件使用url-loader 87 test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 88 loader: 'url-loader', 89 options: { 90 limit: 10000, 91 name: utils.assetsPath('fonts/[name].[hash:7].[ext]') // hash:7 代表 7 位數的 hash 92 } 93 } 94 ] 95 }, 96 node: { 97 // prevent webpack from injecting useless setImmediate polyfill because Vue 98 // source contains it (although only uses it if it's native). 99 setImmediate: false, 100 // prevent webpack from injecting mocks to Node native modules 101 // that does not make sense for the client 102 dgram: 'empty', 103 fs: 'empty', 104 net: 'empty', 105 tls: 'empty', 106 child_process: 'empty' 107 } 108 }
4. 開發環境配置文件 webpack.dev.conf.js
1 'use strict' 2 const utils = require('./utils') 3 const webpack = require('webpack') 4 const config = require('../config') // 基本配置的參數 5 const merge = require('webpack-merge') // webpack-merge是一個可以合並數組和對象的插件 6 const path = require('path') 7 const baseWebpackConfig = require('./webpack.base.conf') // webpack基本配置文件(開發和生產環境公用部分) 8 const CopyWebpackPlugin = require('copy-webpack-plugin') 9 // html-webpack-plugin用於將webpack編譯打包后的產品文件注入到html模板中 10 // 即在index.html里面加上<link>和<script>標簽引用webpack打包后的文件 11 const HtmlWebpackPlugin = require('html-webpack-plugin') 12 // friendly-errors-webpack-plugin用於更友好地輸出webpack的警告、錯誤等信息 13 const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 14 const portfinder = require('portfinder') // 自動檢索下一個可用端口 15 16 const HOST = process.env.HOST 17 const PORT = process.env.PORT && Number(process.env.PORT) ) // 讀取系統環境變量的port 18 19 // 合並baseWebpackConfig配置 20 const devWebpackConfig = merge(baseWebpackConfig, { 21 module: { 22 // 對一些獨立的css文件以及它的預處理文件做一個編譯 23 rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) 24 }, 25 // cheap-module-eval-source-map is faster for development 26 devtool: config.dev.devtool, 27 28 // these devServer options should be customized in /config/index.js 29 devServer: { // webpack-dev-server服務器配置 30 clientLogLevel: 'warning', // console 控制台顯示的消息,可能的值有 none, error, warning 或者 info 31 historyApiFallback: { 32 rewrites: [ 33 { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }, 34 ], 35 }, 36 hot: true, // 開啟熱模塊加載 37 contentBase: false, // since we use CopyWebpackPlugin. 38 compress: true, 39 host: HOST || config.dev.host, // process.env 優先 40 port: PORT || config.dev.port, // process.env 優先 41 open: config.dev.autoOpenBrowser, 42 overlay: config.dev.errorOverlay 43 ? { warnings: false, errors: true } 44 : false, 45 publicPath: config.dev.assetsPublicPath, 46 proxy: config.dev.proxyTable, // 代理設置 47 quiet: true, // necessary for FriendlyErrorsPlugin 48 watchOptions: { // 啟用 Watch 模式。這意味着在初始構建之后,webpack 將繼續監聽任何已解析文件的更改 49 poll: config.dev.poll, // 通過傳遞 true 開啟 polling,或者指定毫秒為單位進行輪詢。默認為false 50 } 51 }, 52 plugins: [ 53 new webpack.DefinePlugin({ 54 'process.env': require('../config/dev.env') 55 }), 56 /*模塊熱替換它允許在運行時更新各種模塊,而無需進行完全刷新*/ 57 new webpack.HotModuleReplacementPlugin(), 58 new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. 59 new webpack.NoEmitOnErrorsPlugin(),// 跳過編譯時出錯的代碼並記錄下來,主要作用是使編譯后運行時的包不出錯 60 // https://github.com/ampedandwired/html-webpack-plugin 61 new HtmlWebpackPlugin({ 62 // 指定編譯后生成的html文件名 63 filename: 'index.html', 64 // 需要處理的模板 65 template: 'index.html', 66 // 打包過程中輸出的js、css的路徑添加到html文件中 67 // css文件插入到head中 68 // js文件插入到body中,可能的選項有 true, 'head', 'body', false 69 inject: true 70 }), 71 // copy custom static assets 72 new CopyWebpackPlugin([ 73 { 74 from: path.resolve(__dirname, '../static'), 75 to: config.dev.assetsSubDirectory, 76 ignore: ['.*'] 77 } 78 ]) 79 ] 80 }) 81 82 module.exports = new Promise((resolve, reject) => { 83 portfinder.basePort = process.env.PORT || config.dev.port // 獲取當前設定的端口 84 portfinder.getPort((err, port) => { 85 if (err) { 86 reject(err) 87 } else { 88 // publish the new Port, necessary for e2e tests 發布新的端口,對於e2e測試 89 process.env.PORT = port 90 // add port to devServer config 91 devWebpackConfig.devServer.port = port 92 93 // Add FriendlyErrorsPlugin 94 devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ 95 compilationSuccessInfo: { 96 messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], 97 }, 98 onErrors: config.dev.notifyOnErrors 99 ? utils.createNotifierCallback() 100 : undefined 101 })) 102 103 resolve(devWebpackConfig) 104 } 105 }) 106 })
5. 生產模式配置文件 webpack.prod.conf.js
1 'use strict' 2 const path = require('path') 3 const utils = require('./utils') 4 const webpack = require('webpack') 5 const config = require('../config') 6 const merge = require('webpack-merge') 7 const baseWebpackConfig = require('./webpack.base.conf') 8 // copy-webpack-plugin,用於將static中的靜態文件復制到產品文件夾dist 9 const CopyWebpackPlugin = require('copy-webpack-plugin') 10 const HtmlWebpackPlugin = require('html-webpack-plugin') 11 const ExtractTextPlugin = require('extract-text-webpack-plugin') 12 // optimize-css-assets-webpack-plugin,用於優化和最小化css資源 13 const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 14 // uglifyJs 混淆js插件 15 const UglifyJsPlugin = require('uglifyjs-webpack-plugin') 16 17 const env = process.env.NODE_ENV === 'testing' 18 ? require('../config/test.env') 19 : require('../config/prod.env') 20 21 const webpackConfig = merge(baseWebpackConfig, { 22 module: { 23 // 樣式文件的處理規則,對css/sass/scss等不同內容使用相應的styleLoaders 24 // 由utils配置出各種類型的預處理語言所需要使用的loader,例如sass需要使用sass-loader 25 rules: utils.styleLoaders({ 26 sourceMap: config.build.productionSourceMap, 27 extract: true, 28 usePostCSS: true 29 }) 30 }, 31 devtool: config.build.productionSourceMap ? config.build.devtool : false, 32 // webpack輸出路徑和命名規則 33 output: { 34 path: config.build.assetsRoot, 35 filename: utils.assetsPath('js/[name].[chunkhash].js'), 36 chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 37 }, 38 plugins: [ 39 // http://vuejs.github.io/vue-loader/en/workflow/production.html 40 new webpack.DefinePlugin({ 41 'process.env': env 42 }), 43 // 丑化壓縮JS代碼 44 new UglifyJsPlugin({ 45 uglifyOptions: { 46 compress: { 47 warnings: false 48 } 49 }, 50 sourceMap: config.build.productionSourceMap, 51 parallel: true 52 }), 53 // extract css into its own file 54 // 將css提取到單獨的文件 55 new ExtractTextPlugin({ 56 filename: utils.assetsPath('css/[name].[contenthash].css'), 57 // Setting the following option to `false` will not extract CSS from codesplit chunks. 58 // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack. 59 // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 60 // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110 61 allChunks: true, 62 }), 63 // Compress extracted CSS. We are using this plugin so that possible 64 // duplicated CSS from different components can be deduped. 65 // 優化、最小化css代碼,如果只簡單使用extract-text-plugin可能會造成css重復 66 // 具體原因可以看npm上面optimize-css-assets-webpack-plugin的介紹 67 new OptimizeCSSPlugin({ 68 cssProcessorOptions: config.build.productionSourceMap 69 ? { safe: true, map: { inline: false } } 70 : { safe: true } 71 }), 72 // generate dist index.html with correct asset hash for caching. 73 // you can customize output by editing /index.html 74 // see https://github.com/ampedandwired/html-webpack-plugin 75 // 將產品文件的引用注入到index.html 76 new HtmlWebpackPlugin({ 77 filename: process.env.NODE_ENV === 'testing' 78 ? 'index.html' 79 : config.build.index, 80 template: 'index.html', 81 inject: true, 82 minify: { 83 // 刪除index.html中的注釋 84 removeComments: true, 85 // 刪除index.html中的空格 86 collapseWhitespace: true, 87 // 刪除各種html標簽屬性值的雙引號 88 removeAttributeQuotes: true 89 // more options: 90 // https://github.com/kangax/html-minifier#options-quick-reference 91 }, 92 // necessary to consistently work with multiple chunks via CommonsChunkPlugin 93 // 注入依賴的時候按照依賴先后順序進行注入,比如,需要先注入vendor.js,再注入app.js 94 chunksSortMode: 'dependency' 95 }), 96 // keep module.id stable when vendor modules does not change 97 new webpack.HashedModuleIdsPlugin(), 98 // enable scope hoisting 99 new webpack.optimize.ModuleConcatenationPlugin(), 100 // split vendor js into its own file 101 // 將所有從node_modules中引入的js提取到vendor.js,即抽取庫文件 102 new webpack.optimize.CommonsChunkPlugin({ 103 name: 'vendor', 104 minChunks (module) { 105 // any required modules inside node_modules are extracted to vendor 106 return ( 107 module.resource && 108 /\.js$/.test(module.resource) && 109 module.resource.indexOf( 110 path.join(__dirname, '../node_modules') 111 ) === 0 112 ) 113 } 114 }), 115 // extract webpack runtime and module manifest to its own file in order to 116 // prevent vendor hash from being updated whenever app bundle is updated 117 // 從vendor中提取出manifest,原因如上 118 new webpack.optimize.CommonsChunkPlugin({ 119 name: 'manifest', 120 minChunks: Infinity 121 }), 122 // This instance extracts shared chunks from code splitted chunks and bundles them 123 // in a separate chunk, similar to the vendor chunk 124 // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk 125 new webpack.optimize.CommonsChunkPlugin({ 126 name: 'app', 127 async: 'vendor-async', 128 children: true, 129 minChunks: 3 130 }), 131 132 // copy custom static assets 133 // 將static文件夾里面的靜態資源復制到dist/static 134 new CopyWebpackPlugin([ 135 { 136 from: path.resolve(__dirname, '../static'), 137 to: config.build.assetsSubDirectory, 138 ignore: ['.*'] 139 } 140 ]) 141 ] 142 }) 143 144 // 如果開啟了產品gzip壓縮,則利用插件將構建后的產品文件進行壓縮 145 if (config.build.productionGzip) { 146 // 一個用於壓縮的webpack插件 147 const CompressionWebpackPlugin = require('compression-webpack-plugin') 148 149 webpackConfig.plugins.push( 150 new CompressionWebpackPlugin({ 151 asset: '[path].gz[query]', 152 // 壓縮算法 153 algorithm: 'gzip', 154 test: new RegExp( 155 '\\.(' + 156 config.build.productionGzipExtensions.join('|') + 157 ')$' 158 ), 159 threshold: 10240, 160 minRatio: 0.8 161 }) 162 ) 163 } 164 165 // 如果啟動了report,則通過插件給出webpack構建打包后的產品文件分析報告 166 if (config.build.bundleAnalyzerReport) { 167 const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 168 webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 169 } 170 171 module.exports = webpackConfig
6. build.js 編譯入口
1 'use strict' 2 require('./check-versions')() 3 4 process.env.NODE_ENV = 'production' 5 // ora,一個可以在終端顯示spinner的插件 6 const ora = require('ora') 7 // rm,用於刪除文件或文件夾的插件 8 const rm = require('rimraf') 9 const path = require('path') 10 // chalk,用於在控制台輸出帶顏色字體的插件 11 const chalk = require('chalk') 12 const webpack = require('webpack') 13 const config = require('../config') 14 const webpackConfig = require('./webpack.prod.conf') 15 16 const spinner = ora('building for production...') 17 spinner.start() // 開啟loading動畫 18 19 // 首先將整個dist文件夾以及里面的內容刪除,以免遺留舊的沒用的文件 20 // 刪除完成后才開始webpack構建打包 21 rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 22 if (err) throw err 23 // 執行webpack構建打包,完成之后在終端輸出構建完成的相關信息或者輸出報錯信息並退出程序 24 webpack(webpackConfig, (err, stats) => { 25 spinner.stop() 26 if (err) throw err 27 process.stdout.write(stats.toString({ 28 colors: true, 29 modules: false, 30 children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. 31 chunks: false, 32 chunkModules: false 33 }) + '\n\n') 34 35 if (stats.hasErrors()) { 36 console.log(chalk.red(' Build failed with errors.\n')) 37 process.exit(1) 38 } 39 40 console.log(chalk.cyan(' Build complete.\n')) 41 console.log(chalk.yellow( 42 ' Tip: built files are meant to be served over an HTTP server.\n' + 43 ' Opening index.html over file:// won\'t work.\n' 44 )) 45 }) 46 })
7. 實用代碼段 utils.js
1 'use strict' 2 const path = require('path') 3 const config = require('../config') 4 // extract-text-webpack-plugin可以提取bundle中的特定文本,將提取后的文本單獨存放到另外的文件 5 // 這里用來提取css樣式 6 const ExtractTextPlugin = require('extract-text-webpack-plugin') 7 const packageConfig = require('../package.json') 8 9 // 資源文件的存放路徑 10 exports.assetsPath = function (_path) { 11 const assetsSubDirectory = process.env.NODE_ENV === 'production' 12 ? config.build.assetsSubDirectory 13 : config.dev.assetsSubDirectory 14 15 return path.posix.join(assetsSubDirectory, _path) 16 } 17 18 // 生成css、sass、scss等各種用來編寫樣式的語言所對應的loader配置 19 exports.cssLoaders = function (options) { 20 options = options || {} 21 // css-loader配置 22 const cssLoader = { 23 loader: 'css-loader', 24 options: { 25 // 是否使用source-map 26 sourceMap: options.sourceMap 27 } 28 } 29 30 const postcssLoader = { 31 loader: 'postcss-loader', 32 options: { 33 sourceMap: options.sourceMap 34 } 35 } 36 37 // generate loader string to be used with extract text plugin 38 // 生成各種loader配置,並且配置了extract-text-pulgin 39 function generateLoaders (loader, loaderOptions) { 40 const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] 41 // 例如generateLoaders('less'),這里就會push一個less-loader 42 // less-loader先將less編譯成css,然后再由css-loader去處理css 43 // 其他sass、scss等語言也是一樣的過程 44 if (loader) { 45 loaders.push({ 46 loader: loader + '-loader', 47 options: Object.assign({}, loaderOptions, { 48 sourceMap: options.sourceMap 49 }) 50 }) 51 } 52 53 // Extract CSS when that option is specified 54 // (which is the case during production build) 55 if (options.extract) { 56 // 配置extract-text-plugin提取樣式 57 return ExtractTextPlugin.extract({ 58 use: loaders, 59 fallback: 'vue-style-loader' 60 }) 61 } else { 62 // 無需提取樣式則簡單使用vue-style-loader配合各種樣式loader去處理<style>里面的樣式 63 return ['vue-style-loader'].concat(loaders) 64 } 65 } 66 67 // https://vue-loader.vuejs.org/en/configurations/extract-css.html 68 // 得到各種不同處理樣式的語言所對應的loader 69 return { 70 css: generateLoaders(), 71 postcss: generateLoaders(), 72 less: generateLoaders('less'), 73 sass: generateLoaders('sass', { indentedSyntax: true }), 74 scss: generateLoaders('sass'), 75 stylus: generateLoaders('stylus'), 76 styl: generateLoaders('stylus') 77 } 78 } 79 80 // Generate loaders for standalone style files (outside of .vue) 81 // 生成處理單獨的.css、.sass、.scss等樣式文件的規則 82 exports.styleLoaders = function (options) { 83 const output = [] 84 const loaders = exports.cssLoaders(options) 85 86 for (const extension in loaders) { 87 const loader = loaders[extension] 88 output.push({ 89 test: new RegExp('\\.' + extension + '$'), 90 use: loader 91 }) 92 } 93 94 return output 95 } 96 97 exports.createNotifierCallback = () => { 98 const notifier = require('node-notifier') 99 100 return (severity, errors) => { 101 if (severity !== 'error') return 102 103 const error = errors[0] 104 const filename = error.file && error.file.split('!').pop() 105 106 notifier.notify({ 107 title: packageConfig.name, 108 message: severity + ': ' + error.name, 109 subtitle: filename || '', 110 icon: path.join(__dirname, 'logo.png') 111 }) 112 } 113 }
8. babel配置文件.babelrc
1 { //設定轉碼規則 2 "presets": [ 3 ["env", { 4 "modules": false, 5 //對BABEL_ENV或者NODE_ENV指定的不同的環境變量,進行不同的編譯操作 6 "targets": { 7 "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] 8 } 9 }], 10 "stage-2" 11 ], 12 //轉碼用的插件 13 "plugins": ["transform-vue-jsx", "transform-runtime"] 14 }
9 .編碼規范.editorconfig (自定義)
1 root = true 2 3 [*] // 對所有文件應用下面的規則 4 charset = utf-8 // 編碼規則用utf-8 5 indent_style = space // 縮進用空格 6 indent_size = 2 // 縮進數量為2個空格 7 end_of_line = lf // 換行符格式 8 insert_final_newline = true // 是否在文件的最后插入一個空行 9 trim_trailing_whitespace = true // 是否刪除行尾的空格
10 .src/app.vue文件解讀
1 <template> 2 <div id="app"> 3 <img src="./assets/logo.png"> 4 <router-view></router-view> 5 </div> 6 </template> 7 8 <script> 9 export default { 10 name: 'app' 11 } 12 </script> 13 14 <style> 15 #app { 16 font-family: 'Avenir', Helvetica, Arial, sans-serif; 17 -webkit-font-smoothing: antialiased; 18 -moz-osx-font-smoothing: grayscale; 19 text-align: center; 20 color: #2c3e50; 21 margin-top: 60px; 22 } 23 </style>
<template></template> 標簽包裹的內容:這是模板的HTMLDom結構
<script></script> 標簽包括的js內容:你可以在這里寫一些頁面的js的邏輯代碼。
<style></style> 標簽包裹的css內容:頁面需要的CSS樣式。
11. src/router/index.js 路由文件
1 import Vue from 'vue' 2 import Router from 'vue-router' 3 import Hello from '@/components/Hello' 4 5 Vue.use(Router) 6 7 export default new Router({ 8 routes: [//配置路由 9 { 10 path: '/', //訪問路徑 11 name: 'Hello', //路由名稱 12 component: Hello //路由需要的組件(駝峰式命名) 13 } 14 ]
12. eslint的相關配置(按照AirBnb的規則檢測);