vue-cli(这可能是)最全的解析了(vue 教程四)

原文地址在底部

这可能是vue-cli最全的解析了……

题言:

相信很多vue新手,都像我一样,只是知道可以用vue-cli直接生成一个vue项目的架构,并不明白,他究竟是怎么运行的,现在我们一起来研究一下。。。

一、安装vue-cli,相信你既然会用到vue-cli,自然node环境是OK的,直接命令行下安装

npm install -g vue-cli


二、使用vue-cli创建vue项目

用法: vue init

1template-name:2    . webpack3. 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'  2const path = require('path')  3const utils = require('./utils')  4const config = require('../config')  5const vueLoaderConfig = require('./vue-loader.conf')  6  7// 获取绝对路径  8function resolve (dir) {  9returnpath.join(__dirname, '..', dir) 10} 11 12const createLintingRule = () => ({ 13test: /\.(js|vue)$/, 14loader: 'eslint-loader', 15enforce: 'pre', 16include: [resolve('src'), resolve('test')], 17  options: { 18formatter: require('eslint-friendly-formatter'), 19emitWarning: !config.dev.showEslintErrorsInOverlay 20  } 21}) 22 23module.exports = { 24// 基础上下文 25context: path.resolve(__dirname, '../'), 26// webpack的入口文件 27  entry: { 28app: './src/main.js' 29  }, 30// webpack的输出文件 31  output: { 32    path: config.build.assetsRoot, 33filename: '[name].js', 34publicPath: 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: { 46extensions: ['.js', '.vue', '.json'], 47alias: {// 创建别名 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进行编译 57test: /\.vue$/, 58loader: 'vue-loader', 59        options: vueLoaderConfig 60      }, 61{// 对src和test文件夹下的.js文件使用babel-loader将es6+的代码转成es5 62test: /\.js$/, 63loader: 'babel-loader', 64include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] 65      }, 66{// 对图片资源文件使用url-loader 67test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 68loader: 'url-loader', 69        options: { 70// 小于10K的图片转成base64编码的dataURL字符串写到代码中 71limit: 10000, 72// 其他的图片转移到静态资源文件夹 73name: utils.assetsPath('img/[name].[hash:7].[ext]') 74        } 75      }, 76{// 对多媒体资源文件使用url-loader 77test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 78loader: 'url-loader', 79        options: { 80// 小于10K的资源转成base64编码的dataURL字符串写到代码中 81limit: 10000, 82// 其他的资源转移到静态资源文件夹 83name: utils.assetsPath('media/[name].[hash:7].[ext]') 84        } 85      }, 86{// 对字体资源文件使用url-loader 87test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 88loader: 'url-loader', 89        options: { 90limit: 10000, 91name: 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). 99setImmediate:false,100// prevent webpack from injecting mocks to Node native modules101// that does not make sense for the client102dgram: 'empty',103fs: 'empty',104net: 'empty',105tls: 'empty',106child_process: 'empty'107  }108}


4. 开发环境配置文件 webpack.dev.conf.js

  1'use strict'  2const utils = require('./utils')  3const webpack = require('webpack')  4const config = require('../config')// 基本配置的参数  5const merge = require('webpack-merge')// webpack-merge是一个可以合并数组和对象的插件  6const path = require('path')  7const baseWebpackConfig = require('./webpack.base.conf')// webpack基本配置文件(开发和生产环境公用部分)  8const CopyWebpackPlugin = require('copy-webpack-plugin')  9// html-webpack-plugin用于将webpack编译打包后的产品文件注入到html模板中 10// 即在index.html里面加上<link>和<script>标签引用webpack打包后的文件 11const HtmlWebpackPlugin = require('html-webpack-plugin') 12// friendly-errors-webpack-plugin用于更友好地输出webpack的警告、错误等信息 13const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 14const portfinder = require('portfinder')// 自动检索下一个可用端口 15 16const HOST = process.env.HOST 17const PORT = process.env.PORT && Number(process.env.PORT) )// 读取系统环境变量的port 18 19// 合并baseWebpackConfig配置 20const devWebpackConfig = merge(baseWebpackConfig, { 21  module: { 22// 对一些独立的css文件以及它的预处理文件做一个编译 23rules: 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 29devServer: {//  webpack-dev-server服务器配置 30clientLogLevel: 'warning',// console 控制台显示的消息,可能的值有 none, error, warning 或者 info 31    historyApiFallback: { 32      rewrites: [ 33{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }, 34      ], 35    }, 36hot:true,// 开启热模块加载 37contentBase:false,// since we use CopyWebpackPlugin. 38compress:true, 39host: HOST || config.dev.host,// process.env 优先 40port: 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, 46proxy: config.dev.proxyTable,// 代理设置 47quiet:true,// necessary for FriendlyErrorsPlugin 48watchOptions: {// 启用 Watch 模式。这意味着在初始构建之后,webpack 将继续监听任何已解析文件的更改 49poll: config.dev.poll,// 通过传递 true 开启 polling,或者指定毫秒为单位进行轮询。默认为false 50    } 51  }, 52  plugins: [ 53new webpack.DefinePlugin({ 54'process.env': require('../config/dev.env') 55    }), 56/*模块热替换它允许在运行时更新各种模块,而无需进行完全刷新*/ 57new webpack.HotModuleReplacementPlugin(), 58newwebpack.NamedModulesPlugin(),// HMR shows correct file names in console on update. 59newwebpack.NoEmitOnErrorsPlugin(),// 跳过编译时出错的代码并记录下来,主要作用是使编译后运行时的包不出错 60// https://github.com/ampedandwired/html-webpack-plugin 61new HtmlWebpackPlugin({ 62// 指定编译后生成的html文件名 63filename: 'index.html', 64// 需要处理的模板 65template: 'index.html', 66// 打包过程中输出的js、css的路径添加到html文件中 67// css文件插入到head中 68// js文件插入到body中,可能的选项有 true, 'head', 'body', false 69inject:true 70    }), 71// copy custom static assets 72new CopyWebpackPlugin([ 73      { 74from: path.resolve(__dirname, '../static'), 75        to: config.dev.assetsSubDirectory, 76ignore: ['.*'] 77      } 78    ]) 79  ] 80}) 81 82module.exports =newPromise((resolve, reject) => { 83portfinder.basePort = process.env.PORT || config.dev.port// 获取当前设定的端口 84portfinder.getPort((err, port) => { 85if (err) { 86      reject(err) 87}else { 88// publish the new Port, necessary for e2e tests  发布新的端口,对于e2e测试 89process.env.PORT = port 90// add port to devServer config 91devWebpackConfig.devServer.port = port 92 93// Add FriendlyErrorsPlugin 94devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ 95        compilationSuccessInfo: { 96messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], 97        }, 98        onErrors: config.dev.notifyOnErrors 99? utils.createNotifierCallback()100        : undefined101      }))102103      resolve(devWebpackConfig)104    }105  })106})


5. 生产模式配置文件 webpack.prod.conf.js

  1'use strict'  2const path = require('path')  3const utils = require('./utils')  4const webpack = require('webpack')  5const config = require('../config')  6const merge = require('webpack-merge')  7const baseWebpackConfig = require('./webpack.base.conf')  8// copy-webpack-plugin,用于将static中的静态文件复制到产品文件夹dist  9const CopyWebpackPlugin = require('copy-webpack-plugin') 10const HtmlWebpackPlugin = require('html-webpack-plugin') 11const ExtractTextPlugin = require('extract-text-webpack-plugin') 12// optimize-css-assets-webpack-plugin,用于优化和最小化css资源 13const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 14// uglifyJs 混淆js插件 15const UglifyJsPlugin = require('uglifyjs-webpack-plugin') 16 17const env = process.env.NODE_ENV === 'testing' 18? require('../config/test.env') 19: require('../config/prod.env') 20 21const 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, 27extract:true, 28usePostCSS:true 29    }) 30  }, 31devtool: config.build.productionSourceMap ? config.build.devtool :false, 32// webpack输出路径和命名规则 33  output: { 34    path: config.build.assetsRoot, 35filename: utils.assetsPath('js/[name].[chunkhash].js'), 36chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 37  }, 38  plugins: [ 39// http://vuejs.github.io/vue-loader/en/workflow/production.html 40new webpack.DefinePlugin({ 41'process.env': env 42    }), 43// 丑化压缩JS代码 44new UglifyJsPlugin({ 45      uglifyOptions: { 46        compress: { 47warnings:false 48        } 49      }, 50      sourceMap: config.build.productionSourceMap, 51parallel:true 52    }), 53// extract css into its own file 54// 将css提取到单独的文件 55new ExtractTextPlugin({ 56filename: 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 61allChunks: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的介绍 67new 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 76new HtmlWebpackPlugin({ 77filename: process.env.NODE_ENV === 'testing' 78? 'index.html' 79        : config.build.index, 80template: 'index.html', 81inject:true, 82      minify: { 83// 删除index.html中的注释 84removeComments:true, 85// 删除index.html中的空格 86collapseWhitespace:true, 87// 删除各种html标签属性值的双引号 88removeAttributeQuotes: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 94chunksSortMode: 'dependency' 95    }), 96// keep module.id stable when vendor modules does not change 97new webpack.HashedModuleIdsPlugin(), 98// enable scope hoisting 99new webpack.optimize.ModuleConcatenationPlugin(),100// split vendor js into its own file101// 将所有从node_modules中引入的js提取到vendor.js,即抽取库文件102new webpack.optimize.CommonsChunkPlugin({103name: 'vendor',104      minChunks (module) {105// any required modules inside node_modules are extracted to vendor106return (107module.resource &&108/\.js$/.test(module.resource) &&109          module.resource.indexOf(110path.join(__dirname, '../node_modules')111) === 0112        )113      }114    }),115// extract webpack runtime and module manifest to its own file in order to116// prevent vendor hash from being updated whenever app bundle is updated117// 从vendor中提取出manifest,原因如上118new webpack.optimize.CommonsChunkPlugin({119name: 'manifest',120      minChunks: Infinity121    }),122// This instance extracts shared chunks from code splitted chunks and bundles them123// in a separate chunk, similar to the vendor chunk124// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk125new webpack.optimize.CommonsChunkPlugin({126name: 'app',127async: 'vendor-async',128children:true,129minChunks: 3130    }),131132// copy custom static assets133// 将static文件夹里面的静态资源复制到dist/static134new CopyWebpackPlugin([135      {136from: path.resolve(__dirname, '../static'),137        to: config.build.assetsSubDirectory,138ignore: ['.*']139      }140    ])141  ]142})143144// 如果开启了产品gzip压缩,则利用插件将构建后的产品文件进行压缩145if (config.build.productionGzip) {146// 一个用于压缩的webpack插件147const CompressionWebpackPlugin = require('compression-webpack-plugin')148149  webpackConfig.plugins.push(150new CompressionWebpackPlugin({151asset: '[path].gz[query]',152// 压缩算法153algorithm: 'gzip',154test:new RegExp(155'\\.(' +156config.build.productionGzipExtensions.join('|') +157')$'158      ),159threshold: 10240,160minRatio: 0.8161    })162  )163}164165// 如果启动了report,则通过插件给出webpack构建打包后的产品文件分析报告166if (config.build.bundleAnalyzerReport) {167const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin168webpackConfig.plugins.push(new BundleAnalyzerPlugin())169}170171module.exports = webpackConfig


6. build.js 编译入口

1'use strict' 2require('./check-versions')() 3 4process.env.NODE_ENV = 'production' 5// ora,一个可以在终端显示spinner的插件 6const ora = require('ora') 7// rm,用于删除文件或文件夹的插件 8const rm = require('rimraf') 9const path = require('path')10// chalk,用于在控制台输出带颜色字体的插件11const chalk = require('chalk')12const webpack = require('webpack')13const config = require('../config')14const webpackConfig = require('./webpack.prod.conf')1516const spinner = ora('building for production...')17spinner.start()// 开启loading动画1819// 首先将整个dist文件夹以及里面的内容删除,以免遗留旧的没用的文件20// 删除完成后才开始webpack构建打包21rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {22if(err)throw err23// 执行webpack构建打包,完成之后在终端输出构建完成的相关信息或者输出报错信息并退出程序24webpack(webpackConfig, (err, stats) => {25    spinner.stop()26if(err)throw err27    process.stdout.write(stats.toString({28colors:true,29modules:false,30children:false,// If you are using ts-loader, setting this to true will make TypeScript errors show up during build.31chunks:false,32chunkModules:false33}) + '\n\n')3435if (stats.hasErrors()) {36console.log(chalk.red('  Build failed with errors.\n'))37process.exit(1)38    }3940console.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'  2const path = require('path')  3const config = require('../config')  4// extract-text-webpack-plugin可以提取bundle中的特定文本,将提取后的文本单独存放到另外的文件  5// 这里用来提取css样式  6const ExtractTextPlugin = require('extract-text-webpack-plugin')  7const packageConfig = require('../package.json')  8  9// 资源文件的存放路径 10exports.assetsPath =function (_path) { 11const assetsSubDirectory = process.env.NODE_ENV === 'production' 12? config.build.assetsSubDirectory 13    : config.dev.assetsSubDirectory 14 15return path.posix.join(assetsSubDirectory, _path) 16} 17 18// 生成css、sass、scss等各种用来编写样式的语言所对应的loader配置 19exports.cssLoaders =function (options) { 20options = options || {} 21// css-loader配置 22const cssLoader = { 23loader: 'css-loader', 24    options: { 25// 是否使用source-map 26      sourceMap: options.sourceMap 27    } 28  } 29 30const postcssLoader = { 31loader: '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 39function generateLoaders (loader, loaderOptions) { 40const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] 41// 例如generateLoaders('less'),这里就会push一个less-loader 42// less-loader先将less编译成css,然后再由css-loader去处理css 43// 其他sass、scss等语言也是一样的过程 44if (loader) { 45      loaders.push({ 46loader: 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) 55if (options.extract) { 56// 配置extract-text-plugin提取样式 57return ExtractTextPlugin.extract({ 58        use: loaders, 59fallback: 'vue-style-loader' 60      }) 61}else { 62// 无需提取样式则简单使用vue-style-loader配合各种样式loader去处理<style>里面的样式 63return['vue-style-loader'].concat(loaders) 64    } 65  } 66 67// https://vue-loader.vuejs.org/en/configurations/extract-css.html 68// 得到各种不同处理样式的语言所对应的loader 69return { 70    css: generateLoaders(), 71    postcss: generateLoaders(), 72less: generateLoaders('less'), 73sass: generateLoaders('sass', { indentedSyntax:true }), 74scss: generateLoaders('sass'), 75stylus: generateLoaders('stylus'), 76styl: generateLoaders('stylus') 77  } 78} 79 80// Generate loaders for standalone style files (outside of .vue) 81// 生成处理单独的.css、.sass、.scss等样式文件的规则 82exports.styleLoaders =function (options) { 83const output = [] 84const loaders = exports.cssLoaders(options) 85 86for(const extensionin loaders) { 87const loader = loaders[extension] 88    output.push({ 89test:newRegExp('\\.' + extension + '$'), 90      use: loader 91    }) 92  } 93 94return output 95} 96 97exports.createNotifierCallback = () => { 98const notifier = require('node-notifier') 99100return(severity, errors) => {101if(severity !== 'error')return102103const error = errors[0]104const filename = error.file && error.file.split('!').pop()105106    notifier.notify({107      title: packageConfig.name,108message: severity + ': ' + error.name,109subtitle: filename || '',110icon: 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 (自定义)

1root =true23[*]// 对所有文件应用下面的规则4charset = utf-8// 编码规则用utf-85indent_style = space// 缩进用空格6indent_size = 2// 缩进数量为2个空格7end_of_line = lf// 换行符格式8insert_final_newline =true// 是否在文件的最后插入一个空行9trim_trailing_whitespace =true// 是否删除行尾的空格

10 .src/app.vue文件解读

1 2

3 4 5
6 7 8 9exportdefault {10name: 'app'11}12131415#app {16font-family: 'Avenir', Helvetica, Arial, sans-serif;17-webkit-font-smoothing: antialiased;18-moz-osx-font-smoothing: grayscale;19text-align: center;20  color: #2c3e50;21margin-top: 60px;22}23

标签包裹的内容:这是模板的HTMLDom结构标签包括的js内容:你可以在这里写一些页面的js的逻辑代码。标签包裹的css内容:页面需要的CSS样式。

11. src/router/index.js 路由文件

1import Vue from 'vue' 2import Router from 'vue-router' 3import Hello from '@/components/Hello' 4 5Vue.use(Router) 6 7exportdefaultnew Router({ 8routes: [//配置路由 9    {10path: '/',//访问路径11name: 'Hello',//路由名称12component: Hello//路由需要的组件(驼峰式命名)13    }14]


12. eslint的相关配置(按照AirBnb的规则检测);


本文地址http://www.cnblogs.com/zhaowy/

版权声明:本文为原创文章,版权归 作者所有,欢迎分享本文,转载请保留出处!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259