赞
踩
安装vue-cli首先需要安装node,如果你的电脑已经安装node,就可以使用node自带的npm来安装vue-cli
你可以在命令行工具里输入node -v, npm -v 检测你是否安装了npm和版本情况。出现版本号说明你已经安装了npm和node
npm install vue-cli -g
-g :代表全局安装。安装完成后,命令行输入vue -V来进行查看 vue-cli的版本号。注意这里的V是大写的。
vue init webpack my-project 命令说明 :vue init <template-name> <project-name> project-name 是我们要初始化的项目名称 template-name 是表示模板名称,vue-cli官方为我们提供了5种模板,其中webpack是最常用的模板,一般我们开发项目都会用webpack进行开发,而vue官方也推荐我们使用webpack,建议大家学学webpack,还是一个比较有用的前端构建工具。 下面看看其他剩下的几种模板 webpack-simple:一个简单webpack+vue-loader的模板,不包含其他功能。 browserify:一个全面的Browserify+vueify 的模板,功能包括热加载,linting,单元检测。 browserify-simple:一个简单Browserify+vueify的模板,不包含其他功能。 simple:一个最简单的单页应用模板。 $ vue init webpack my-project--- 这个是那个安装vue脚手架的命令 This will install Vue 2.x version of the template. ---这里说明将要创建一个vue 2.x版本的项目 For Vue 1.x use: vue init webpack#1.0 exprice ? Project name (exprice) ---项目名称 ,如果不需要更改直接回车就可以了。注意:这里不能使用大写。 ? Project name exprice ? Project description (A Vue.js project) ---项目描述,默认为A Vue.js project,直接回车,不用编写。 ? Project description A Vue.js project ? Author Datura ---作者,如果你有配置git的作者,他会读取。 ? Author Datura ? Vue build (Use arrow keys) ? Vue build standalone ? Install vue-router? (Y/n) ---是否安装vue的路由插件,Y代表安装,N无需安装,下面的命令也是一样的。 ? Install vue-router? Yes ? Use ESLint to lint your code? (Y/n) n ---是否用ESLint来限制你的代码错误和风格。 ? Use ESLint to lint your code? No ? Setup unit tests with Karma + Mocha? (Y/n) ---是否需要安装单元测试工具Karma+Mocha。 ? Setup unit tests with Karma + Mocha? Yes ? Setup e2e tests with Nightwatch? (Y/n) ---是否安装e2e来进行用户行为模拟测试。 ? Setup e2e tests with Nightwatch? Yes ? Should we run npm install for you after the project has been created? (recommended) npm 这一步会询问你使用npm安装还是yarn安装包依赖,我这里选择的是npm,听说yarn更快更好,童鞋们可以试试,我建议大家使用yarn安装,使用yarn之前确保你的电脑已经安装yarn。以前老版本的vue-cli是没有这个选项的,老版本的vue-cli只是下载vue项目模板,下载完成后需要进入项目文件夹进行包依赖安装,现在vue-cli会帮你安装包依赖,只能说vue真的是越来越人性化了,怪不得这么多人使用vue进行开发。下面截个图 vue-cli · Generated "exprice". To get started: --------------------- 这里说明如何启动这个服务 cd my-project npm run dev
cd my-project
npm run dev
然后打开浏览器地址栏输入 http://localhost:8080 就可以看到尤大大为我们准备的hello-vue的页面,开不开心,高不高兴!
要在项目根目录下找到package.json,然后打开该文件,在文件中的script脚本命令的devNew 行加入–open就可以了。如图所示。然后重新启动项目就可以自动打开浏览器
说明:每个人应用的模板和版本不一样生成的项目目录结构可能和下面的有所区别
|-- build // webpack配置相关配置文件(都已经配置好,一般不需再进行配置) | |-- build.js // 生产环境构建代码 | |-- check-version.js // 版本检查,检查node、npm等版本 | |-- dev-client.js // 开发服务器的热重载(用于实现页面的自动刷新) | |-- dev-server.js // 构建本地服务器(npm run dev) | |-- utils.js // 构建工具相关 | |-- vue-loader.conf.js // webpack loader配置 css加载器配置 | |-- webpack.base.conf.js // webpack基础配置 | |-- webpack.dev.conf.js // webpack开发环境配置,构建开发本地服务器 | |-- webpack.prod.conf.js // webpack生产环境配置 |-- config // vue基本配置文件(如:配置监听端口,打包输出等) | |-- dev.env.js // 开发环境变量 | |-- index.js // 项目一些配置变量(包括监听端口,打包路径等) | |-- prod.env.js // 生产环境变量 |-- node_modules // 依赖包 |-- src // 项目核心文件(我们所有的代码都放在这个文件夹下) | |-- assets // 用来存图片的 | |-- components // vue公共组件 | |-- router // vue的路由管理 | |-- App.vue // 页面入口文件 | |-- main.js // 程序入口文件,加载各种公共组件 |-- static // 静态资源,比如一些图片,json数据等 |-- .babelrc // babel编译参数 ES6语法编译配置 |-- .editorconfig // 代码格式 |-- .gitignore // git上传需要忽略的文件格式 |-- .postcsssrc.js // 转换css的工具 |-- README.md // 项目说明 |-- index.html // 入口页面 |-- package.json // 项目基本信息,包依赖信息等
以上就是vue-cli生成的项目目录结构,虽然看起来有点复杂,但是这并不影响我们进行开发,虽然说我们可以不用关注这些文件是怎么回事也可以进行项目开发,但是可能会影响我们的开发效率,还有一个就是这vue-cli生成的项目结构可能并不满足于我们公司的开发,这时候就要对这个项目进行改造,改成我们想要的结构和拓展相关功能。这时候就需要你看得懂相关的配置文件。
packagejson文件是项目的配置文件,定义了项目的基本信息以及项目的相关包依赖,npm运行命令等,位于项目根目录下。
其中“scripts”定义了一些npm命令 npm run dev 其实就是执行 webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
webpack-dev-server --inline --progress --config build/webpack.dev.conf.js意思就是利用 webpack-dev-server 读取 webpack.dev.conf.js 信息并启动一个本地服务器。这应该也是新版本vue-cli的新特性吧
dependencies 是运行时依赖(生产环境)
devDependencies是开发时的依赖(开发环境)
相应的npm install 在安装 npm 包时,有两种命令参数可以把它们的信息写入 package.json 文件,
–save 会把依赖包名称添加到 package.json 文件 dependencies 键下,
–save-dev 则添加到 package.json 文件 devDependencies 键下。
举个例子,比如我们项目要引用jQuery,因为jQuery部署到线上环境也要使用(生产环境),所以安装jQuery的命令为
npm install jQuery --save
基础的 webpack 配置文件主要根据模式定义了入口出口,以及处理 vue, babel 等的各种模块,是最为基础的部分。其他模式的配置文件以此为基础通过 webpack-merge 合并。
'use strict' const path = require('path'); const utils = require('./utils'); const config = require('../config'); const vueLoaderConfig = require('./vue-loader.conf') function resolve(dir) {//处理路径 return path.join(__dirname, '..', dir); } module.exports = { context: path.resolve(__dirname, '../'), // 基础目录 entry: { app: './src/main.js'//入口文件 }, output: { path: config.build.assetsRoot, // 输出文件,默认'../dist' filename: '[name].js',//输出文件名称, publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath // 生产模式publicpath : config.dev.assetsPublicPath // 开发模式publicpath }, resolve: { // 解析确定的拓展名,方便模块导入 extensions: ['.js', '.vue', '.json'], alias: { // 创建别名 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') // 如 '@/components/HelloWorld' } }, module: {//模块相关配置,包括loader,plugin等 rules: [{ test: /\.vue$/, // vue 要在babel之前 loader: 'vue-loader',//vue转普通的html options: vueLoaderConfig //可选项: vue-loader 选项配置 },{ test: /\.js$/, // babel loader: 'babel-loader',//es6转es5loader include: [resolve('src')] },{ // url-loader 文件大小低于指定的限制时,可返回 DataURL,即base64 test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, // url-loader 图片 loader: 'url-loader', options: { // 兼容性问题需要将query换成options limit: 10000, // 默认无限制 name: utils.assetsPath('img/[name].[hash:7].[ext]') // hash:7 代表 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: { // 是否 polyfill 或 mock setImmediate: false, dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty' } }
我们在启动项目的时候就要用到这个文件,说明这个文件比较重要,大家要好好看一下
'use strict' const utils = require('./utils') const webpack = require('webpack') const config = require('../config')//基本配置的参数 const merge = require('webpack-merge')// 用于合并webpack的配置文件 const baseWebpackConfig = require('./webpack.base.conf')//webpack基本配置文件(开发时和运行时公用) /** * [HtmlWebpackPlugin description] * @type {[type]} * 这个插件的作用是依据一个简单的模板,帮你生成最终的Html5文件, * 这个文件中自动引用了你打包后的JS文件。每次编译都在文件名中插入一个不同的哈希值 */ const HtmlWebpackPlugin = require('html-webpack-plugin') /*能够更好在终端看到webapck运行的警告和错误*/ const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') const portfinder = require('portfinder') // 自动检索下一个可用端口 const HOST = process.env.HOST//读取系统环境变量的host const PORT = process.env.PORT && Number(process.env.PORT)//读取系统环境变量的port // 合并baseWebpackConfig配置 const devWebpackConfig = merge(baseWebpackConfig, { module: { // 对一些独立的css文件以及它的预处理文件做一个编译 rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool,// 添加元信息(meta info)增强调试 // these devServer options should be customized in /config/index.js devServer: {//webpack-dev-server服务器配置 clientLogLevel: 'warning', // console 控制台显示的消息,可能的值有 none, error, warning 或者 info historyApiFallback: true, hot: true,//开启热加载 compress: true,//开启压缩 host: HOST || config.dev.host,// process.env 优先 port: PORT || config.dev.port,// process.env 优先 open: config.dev.autoOpenBrowser,//自动打开浏览器,这里是默认是false,所以不会自动打开 overlay: config.dev.errorOverlay// warning 和 error 都要显示 ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable,//代理设置,用于前后端分离 quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: {//启用 Watch 模式。这意味着在初始构建之后,webpack 将继续监听任何已解析文件的更改 poll: config.dev.poll,//通过传递 true 开启 polling,或者指定毫秒为单位进行轮询。默认为false } }, plugins: [//webpack一些构建用到的插件 new webpack.DefinePlugin({ 'process.env': require('../config/dev.env') }), /*模块热替换它允许在运行时更新各种模块,而无需进行完全刷新*/ new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), // 热加载时直接返回更新的文件名,而不是id new webpack.NoEmitOnErrorsPlugin(),// 跳过编译时出错的代码并记录下来,主要作用是使编译后运行时的包不出错 // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ // 指定编译后生成的html文件名 filename: 'index.html', // 需要处理的模板 template: 'index.html', // 打包过程中输出的js、css的路径添加到html文件中 // css文件插入到head中 // js文件插入到body中,可能的选项有 true, 'head', 'body', false inject: true }), ] }) module.exports = new Promise((resolve, reject) => { portfinder.basePort = process.env.PORT || config.dev.port// 获取当前设定的端口 portfinder.getPort((err, port) => { if (err) { reject(err) } else { // process 发布端口 process.env.PORT = port // 设置 devServer 端口 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) } }) })
'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'); const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin'); const env = process.env.NODE_ENV === 'production' ? require('../config/prod.env') : require('../config/dev.env') const webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, // production 下生成 sourceMap extract: true, // util 中 styleLoaders 方法内的 generateLoaders 函数 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: [ new webpack.DefinePlugin({ 'process.env': env }), new webpack.optimize.UglifyJsPlugin({ // js 代码压缩还可配置 include, cache 等,也可用 babel-minify compress: { warnings: false }, sourceMap: config.build.productionSourceMap, parallel: true // 充分利用多核cpu }), // 提取 js 文件中的 css new ExtractTextPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css'), allChunks: false, }), // 压缩提取出的css new OptimizeCSSPlugin({ cssProcessorOptions: config.build.productionSourceMap ? { safe: true, map: { inline: false } } : { safe: true } }), // 生成 html new HtmlWebpackPlugin({ filename: process.env.NODE_ENV === 'production' ? config.build.index : 'index.html', template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunksSortMode: 'dependency' // 按 dependency 的顺序引入 }), new webpack.HashedModuleIdsPlugin(), // 根据模块的相对路径生成一个四位数的 hash 作为模块 id new webpack.optimize.ModuleConcatenationPlugin(), // 预编译所有模块到一个闭包中 // 拆分公共模块 new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity }), new webpack.optimize.CommonsChunkPlugin({ name: 'app', async: 'vendor-async', children: true, minChunks: 3 }), // 拷贝静态文档 new CopyWebpackPlugin([{ from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] }])] }) if (config.build.productionGzip) { // gzip 压缩 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, // 10kb 以上大小的文件才压缩 minRatio: 0.8 // 最小比例达到 .8 时才压缩 }) ) } if (config.build.bundleAnalyzerReport) { // 可视化分析包的尺寸 const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; webpackConfig.plugins.push(new BundleAnalyzerPlugin()); } module.exports = webpackConfig;
'use strict' process.env.NODE_ENV = 'production'; // 设置当前环境为生产环境 const ora = require('ora'); //loading...进度条 const rm = require('rimraf'); //删除文件 'rm -rf' const chalk = require('chalk'); //stdout颜色设置 const webpack = require('webpack'); const path = require('path'); const config = require('../config'); const webpackConfig = require('./webpack.prod.conf'); const spinner = ora('正在编译...'); spinner.start(); // 清空文件夹 rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err; // 删除完成回调函数内执行编译 webpack(webpackConfig, function (err, stats) { spinner.stop(); if (err) throw err; // 编译完成,输出编译文件 process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n'); //error if (stats.hasErrors()) { console.log(chalk.red(' 编译失败出现错误.\n')); process.exit(1); } //完成 console.log(chalk.cyan(' 编译成功.\n')) console.log(chalk.yellow( ' file:// 无用,需http(s)://.\n' )) }) })
const config = require('../config') const path = require('path') exports.assetsPath = function (_path) { const assetsSubDirectory = process.env.NODE_ENV === 'production' ? config.build.assetsSubDirectory // 'static' : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) // posix方法修正路径 } exports.cssLoaders = function (options) { // 示例: ({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) options = options || {}; // cssLoader const cssLoader = { loader: 'css-loader', options: { sourceMap: options.sourceMap } } // postcssLoader var postcssLoader = { loader: 'postcss-loader', options: { sourceMap: options.sourceMap } } // 生成 loader function generateLoaders (loader, loaderOptions) { const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] // 设置默认loader if (loader) { loaders.push({ loader: loader + '-loader', options: Object.assign({}, loaderOptions, { // 生成 options 对象 sourceMap: options.sourceMap }) }) } // 生产模式中提取css if (options.extract) { // 如果 options 中的 extract 为 true 配合生产模式 return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader' // 默认使用 vue-style-loader }) } else { return ['vue-style-loader'].concat(loaders) } } return { // 返回各种 loaders 对象 css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders('less'), // 示例:[ // { loader: 'css-loader', options: { sourceMap: true/false } }, // { loader: 'postcss-loader', options: { sourceMap: true/false } }, // { loader: 'less-loader', options: { sourceMap: true/false } }, // ] sass: generateLoaders('sass', { indentedSyntax: true }), scss: generateLoaders('sass'), stylus: generateLoaders('stylus'), styl: generateLoaders('stylus') } } 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 }) // 示例: // { // test: new RegExp(\\.less$), // use: { // loader: 'less-loader', options: { sourceMap: true/false } // } // } } return output } exports.createNotifierCallback = function () { // 配合 friendly-errors-webpack-plugin // 基本用法:notifier.notify('message'); const notifier = require('node-notifier'); // 发送跨平台通知系统 return (severity, errors) => { // 当前设定是只有出现 error 错误时触发 notifier 发送通知 if (severity !== 'error') { return } // 严重程度可以是 'error' 或 'warning' const error = errors[0] const filename = error.file && error.file.split('!').pop(); notifier.notify({ title: pkg.name, message: severity + ': ' + error.name, subtitle: filename || '' // icon: path.join(__dirname, 'logo.png') // 通知图标 }) } }
{ //设定转码规则
"presets": [
["env", {
"modules": false,
//对BABEL_ENV或者NODE_ENV指定的不同的环境变量,进行不同的编译操作
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
//转码用的插件
"plugins": ["transform-vue-jsx", "transform-runtime"]
}
root = true
[*] // 对所有文件应用下面的规则
charset = utf-8 // 编码规则用utf-8
indent_style = space // 缩进用空格
indent_size = 2 // 缩进数量为2个空格
end_of_line = lf // 换行符格式
insert_final_newline = true // 是否在文件的最后插入一个空行
trim_trailing_whitespace = true // 是否删除行尾的空格
main.js是整个项目的入口文件
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false //生产环境提示,这里设置成了false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }//引入App组件
})
template>标签包裹的内容:这是模板的HTMLDom结构
script标签包括的js内容:你可以在这里写一些页面的js的逻辑代码。
style标签包裹的css内容:页面需要的CSS样式。
<template> <div id="app"> <img src="./assets/logo.png"> <router-view></router-view> </div> </template> <script> export default { name: 'app' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
Vue.use(Router)
export default new Router({
routes: [//配置路由
{
path: '/',//访问路径
name: 'Hello',//路由名成
component: Hello//路由需要的组件
}
]
})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。