相信不少vue新手,都像我同樣,只是知道能夠用vue-cli直接生成一個vue項目的架構,並不明白,他到底是怎麼運行的,如今咱們一塊兒來研究一下。。。css
npm install -g vue-cli
複製代碼
用法: vue init <template-name> <project-name>
template-name:
. webpack
. webpack-simple // 一個簡單webpack+vue-loader的模板,不包含其餘功能。
. browserify // 一個全面的Browserify+vueify 的模板,功能包括熱加載,linting,單元檢測。
. browserify-simple // 一個簡單Browserify+vueify的模板,不包含其餘功能。
. pwa // 基於webpack模板的vue-cli的PWA模板
. simple // 一個最簡單的單頁應用模板
複製代碼
經常使用的就是webpack了,模板之間的不一樣,本身體驗
示例:html
vue init webpack my-project
複製代碼
執行指令後,會讓用戶輸入幾個基本的選項,如圖所示vue
根據提示,待模板加載完成以後,執行下面兩條命令node
cd my-project
npm run dev // dev表明下圖框選的內容
複製代碼
出現如圖,就是編譯成功了,英文稍微好點,就能讀懂 這時候,鼠標放到 http://localhost:8080 會提示用「Alt+點擊」便可訪問;
出現如圖,就成功建立了項目;webpack
本文主要分析開發(dev)和構建(build)兩個過程涉及到的文件,故下面文件結構僅列出相應的內容。git
|-- 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 // 項目基本信息,包依賴信息等
複製代碼
如圖所示:es6
package.json文件是項目的配置文件,定義了項目的基本信息以及項目的相關包依賴,npm運行命令等github
scripts 裏定義的是一些比較長的命令,用node去執行一段命令,好比web
npm run dev
複製代碼
其實就是執行算法
webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
複製代碼
這句話的意思是利用 webpack-dev-server 讀取 webpack.dev.conf.js 信息並啓動一個本地服務器。
簡單的來講
dependencies 是運行時依賴(生產環境) npm install --save **(package name)
devDependencies 是開發時的依賴(開發環境) npm install --save-dev **(package name)
複製代碼
基礎的 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)
}
<!-- 定義一下代碼檢測的規則 -->
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
module.exports = {
// 基礎上下文
context: path.resolve(__dirname, '../'),
// webpack的入口文件
entry: {
app: './src/main.js'
},
// webpack的輸出文件
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
/**
* 當webpack試圖去加載模塊的時候,它默認是查找以 .js 結尾的文件的,
* 它並不知道 .vue 結尾的文件是什麼鬼玩意兒,
* 因此咱們要在配置文件中告訴webpack,
* 遇到 .vue 結尾的也要去加載,
* 添加 resolve 配置項,以下:
*/
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: { // 建立別名
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'), // 如 '@/components/HelloWorld'
}
},
// 不一樣類型模塊的處理規則 就是用不一樣的loader處理不一樣的文件
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{// 對全部.vue文件使用vue-loader進行編譯
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{// 對src和test文件夾下的.js文件使用babel-loader將es6+的代碼轉成es5
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{// 對圖片資源文件使用url-loader
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
// 小於10K的圖片轉成base64編碼的dataURL字符串寫到代碼中
limit: 10000,
// 其餘的圖片轉移到靜態資源文件夾
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{// 對多媒體資源文件使用url-loader
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
// 小於10K的資源轉成base64編碼的dataURL字符串寫到代碼中
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]') // hash:7 表明 7 位數的 hash
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native). setImmediate: false, // prevent webpack from injecting mocks to Node native modules // that does not make sense for the client 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-merge是一個能夠合併數組和對象的插件
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf') // webpack基本配置文件(開發和生產環境公用部分)
const CopyWebpackPlugin = require('copy-webpack-plugin')
// html-webpack-plugin用於將webpack編譯打包後的產品文件注入到html模板中
// 即在index.html裏面加上<link>和<script>標籤引用webpack打包後的文件
const HtmlWebpackPlugin = require('html-webpack-plugin')
// friendly-errors-webpack-plugin用於更友好地輸出webpack的警告、錯誤等信息
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder') // 自動檢索下一個可用端口
const HOST = process.env.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,
// these devServer options should be customized in /config/index.js
devServer: { // webpack-dev-server服務器配置
clientLogLevel: 'warning', // console 控制檯顯示的消息,可能的值有 none, error, warning 或者 info
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true, // 開啓熱模塊加載
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host, // process.env 優先
port: PORT || config.dev.port, // process.env 優先
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { 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: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
/*模塊熱替換它容許在運行時更新各類模塊,而無需進行徹底刷新*/
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
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
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port // 獲取當前設定的端口
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests 發佈新的端口,對於e2e測試
process.env.PORT = port
// add port to devServer config
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')
// copy-webpack-plugin,用於將static中的靜態文件複製到產品文件夾dist
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// optimize-css-assets-webpack-plugin,用於優化和最小化css資源
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// uglifyJs 混淆js插件
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: {
// 樣式文件的處理規則,對css/sass/scss等不一樣內容使用相應的styleLoaders
// 由utils配置出各類類型的預處理語言所須要使用的loader,例如sass須要使用sass-loader
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
// webpack輸出路徑和命名規則
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 UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
// 將css提取到單獨的文件
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.
// 優化、最小化css代碼,若是隻簡單使用extract-text-plugin可能會形成css重複
// 具體緣由能夠看npm上面optimize-css-assets-webpack-plugin的介紹
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
// 將產品文件的引用注入到index.html
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: true,
minify: {
// 刪除index.html中的註釋
removeComments: true,
// 刪除index.html中的空格
collapseWhitespace: true,
// 刪除各類html標籤屬性值的雙引號
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
// 注入依賴的時候按照依賴前後順序進行注入,好比,須要先注入vendor.js,再注入app.js
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
// 將全部從node_modules中引入的js提取到vendor.js,即抽取庫文件
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
// 從vendor中提取出manifest,緣由如上
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
// 將static文件夾裏面的靜態資源複製到dist/static
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
// 若是開啓了產品gzip壓縮,則利用插件將構建後的產品文件進行壓縮
if (config.build.productionGzip) {
// 一個用於壓縮的webpack插件
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
})
)
}
// 若是啓動了report,則經過插件給出webpack構建打包後的產品文件分析報告
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
複製代碼
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
// ora,一個能夠在終端顯示spinner的插件
const ora = require('ora')
// rm,用於刪除文件或文件夾的插件
const rm = require('rimraf')
const path = require('path')
// chalk,用於在控制檯輸出帶顏色字體的插件
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start() // 開啓loading動畫
// 首先將整個dist文件夾以及裏面的內容刪除,以避免遺留舊的沒用的文件
// 刪除完成後纔開始webpack構建打包
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
// 執行webpack構建打包,完成以後在終端輸出構建完成的相關信息或者輸出報錯信息並退出程序
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
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' )) }) }) 複製代碼
'use strict'
const path = require('path')
const config = require('../config')
// extract-text-webpack-plugin能夠提取bundle中的特定文本,將提取後的文本單獨存放到另外的文件
// 這裏用來提取css樣式
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
// 資源文件的存放路徑
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
// 生成css、sass、scss等各類用來編寫樣式的語言所對應的loader配置
exports.cssLoaders = function (options) {
options = options || {}
// css-loader配置
const cssLoader = {
loader: 'css-loader',
options: {
// 是否使用source-map
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
// 生成各類loader配置,而且配置了extract-text-pulgin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
// 例如generateLoaders('less'),這裏就會push一個less-loader
// less-loader先將less編譯成css,而後再由css-loader去處理css
// 其餘sass、scss等語言也是同樣的過程
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
// 配置extract-text-plugin提取樣式
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
// 無需提取樣式則簡單使用vue-style-loader配合各類樣式loader去處理<style>裏面的樣式
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
// 獲得各類不一樣處理樣式的語言所對應的loader
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
// 生成處理單獨的.css、.sass、.scss等樣式文件的規則
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
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.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 // 是否刪除行尾的空格
複製代碼
<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>
複製代碼
<template></template> 標籤包裹的內容:這是模板的HTMLDom結構
<script></script> 標籤包括的js內容:你能夠在這裏寫一些頁面的js的邏輯代碼。
<style></style> 標籤包裹的css內容:頁面須要的CSS樣式。
複製代碼
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 //路由須要的組件(駝峯式命名)
}
]
複製代碼
網上看了張挺有意思的圖:
vue-cli項目圖:
寫在最後: 關於配置文件的註釋都寫在代碼裏了,能夠單獨Copy出來看,有什麼好的想法或者建議,能夠加我微信,歡迎交流……
原文連接:vue-cli詳細解析
參考文章: