這裏建議剛學vue的同學第一個小案例不要使用vue-cli進行操作,待對基本的api使用的比較順手了之後再進行vue-cli的體驗比較好。本人是一名後端開發人員,接觸前端時間不長,這裏有說的不好的地方,還請大家評論建議下。
1. 安裝必要的環境準備
首先我們要能夠暗轉node.js,這個環境。百度搜索node,進入官網根據自己的操作系統進行下載即可。現在的版本都是自帶npm的了。所以安裝後,環境變量正常情況下會自動配置,開啓一個命令行終端,輸入node,npm,就可以看到相應的信息。那麼說明安裝成功。
2. cnpm
由於我們在國內,所以npm的下載路徑對我們來說是很慢的,因此我們要使用淘寶提供的cnpm鏡像(與maven鏡像是一個效果。)百度搜索cnpm,點擊進行官網,裏面的教程很詳細,這裏也不會囉嗦了。
3. 正式搭建vue-cli
我們首先進行vue-cli的一個下載:
cnpm install -g vue-cli
裏面會跟着將webpack一起下載下來,如果沒有,那麼我們也可以手動自己下載一下webpack就好了,命令相同,只是把vue-cli換成webpack。
下載好之後,進入一個合適的目錄,然後輸入:
vue-cli webpack vuedemo1
webpack參數是指:我們使用webpack的這套模板
Vuedemo1指:我們在此目錄下新建一個名字叫做vuedemo1的目錄並將其作爲項目的跟目錄。
這樣,一個空的vue-cli項目就搭建好了
測試一下,輸入:
npm run dev
默認開啓8080端口,並打開默認瀏覽器,看到一個熟悉的vue的頁面。
4. 配置文件講解
本身對配置文件理解的並不是特別深刻,這裏將自己瞭解的一些配置含義寫出來,共同學習一下。
bulid目錄下面的webpack.base.config.js:這裏一般是一些基礎信息的配置,用過webpack的小夥伴應該都比較熟悉,這裏簡單講解一下各個屬性:
input:代表入口文件,這裏一般指定的是index.html
output:出口文件。
module:這裏一般寫的的針對各個文件的配置的解析loader。
resolve:這裏指其他配置,裏面一般有:alias:起別名,例如:
alias: {
‘vue$’: ‘vue/dist/vue.esm.js’,
‘@’: resolve(‘src’),
‘RegForm’: ‘@/components/RegForm.vue’ //新增
}
我這裏新增一個別名,代表一個路徑,這樣,以後要引入這個vue文件的時候,直接:
import Regfrom from “RegForm”就可以了。
前面加@,因爲默認的配置中將@,取名爲resolve(’src’),解析了絕對路徑。build下面dev-server.js:
// 檢查NodeJS和npm的版本
require('./check-versions')()
// 獲取配置
var config = require('../config')
// 如果Node的環境變量中沒有設置當前的環境(NODE_ENV),則使用config中的配置作爲當前的環境
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
// 一個可以調用默認軟件打開網址、圖片、文件等內容的插件
// 這裏用它來調用默認瀏覽器打開dev-server監聽的端口,例如:localhost:8080
var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
// 一個express中間件,用於將http請求代理到其他服務器
// 例:localhost:8080/api/xxx --> localhost:3000/api/xxx
// 這裏使用該插件可以將前端開發中涉及到的請求代理到API服務器上,方便與服務器對接
var proxyMiddleware = require('http-proxy-middleware')
// 根據 Node 環境來引入相應的 webpack 配置
var webpackConfig = process.env.NODE_ENV === 'testing'
? require('./webpack.prod.conf')
: require('./webpack.dev.conf')
// dev-server 監聽的端口,默認爲config.dev.port設置的端口,即8080
var port = process.env.PORT || config.dev.port
// 用於判斷是否要自動打開瀏覽器的布爾變量,當配置文件中沒有設置自動打開瀏覽器的時候其值爲 false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// 定義 HTTP 代理表,代理到 API 服務器
var proxyTable = config.dev.proxyTable
// 創建1個 express 實例
var app = express()
// 根據webpack配置文件創建Compiler對象
var compiler = webpack(webpackConfig)
// webpack-dev-middleware使用compiler對象來對相應的文件進行編譯和綁定
// 編譯綁定後將得到的產物存放在內存中而沒有寫進磁盤
// 將這個中間件交給express使用之後即可訪問這些編譯後的產品文件
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
// webpack-hot-middleware,用於實現熱重載功能的中間件
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {}
})
// 當html-webpack-plugin提交之後通過熱重載中間件發佈重載動作使得頁面重載
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// 將 proxyTable 中的代理請求配置掛在到express服務器上
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
// 格式化options,例如將'www.example.com'變成{ target: 'www.example.com' }
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
// handle fallback for HTML5 history API
// 重定向不存在的URL,常用於SPA
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
// 使用webpack開發中間件
// 即將webpack編譯後輸出到內存中的文件資源掛到express服務器上
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
// 將熱重載中間件掛在到express服務器上
app.use(hotMiddleware)
// serve pure static assets
// 靜態資源的路徑
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
// 將靜態資源掛到express服務器上
app.use(staticPath, express.static('./static'))
// 應用的地址信息,例如:http://localhost:8080
var uri = 'http://localhost:' + port
// webpack開發中間件合法(valid)之後輸出提示語到控制檯,表明服務器已啓動
devMiddleware.waitUntilValid(function () {
console.log('> Listening at ' + uri + '\n')
})
// 啓動express服務器並監聽相應的端口(8080)
module.exports = app.listen(port, function (err) {
if (err) {
console.log(err)
return
}
// when env is testing, don't need open it
// 如果符合自動打開瀏覽器的條件,則通過opn插件調用系統默認瀏覽器打開對應的地址uri
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri)
}
})
3.build/webpack.dev.conf.js (npm run dev用到的配置文件 )
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
// 一個可以合併數組和對象的插件
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
// 一個用於生成HTML文件並自動注入依賴文件(link/script)的webpack插件
var HtmlWebpackPlugin = require('html-webpack-plugin')
// 用於更友好地輸出webpack的警告、錯誤等信息
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
// 合併基礎的webpack配置
module.exports = merge(baseWebpackConfig, {
// 配置樣式文件的處理規則,使用styleLoaders
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// 配置Source Maps。在開發中使用cheap-module-eval-source-map更快
devtool: '#cheap-module-eval-source-map',
// 配置webpack插件
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
// 後頁面中的報錯不會阻塞,但是會在編譯結束後報錯
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
]
})
4.build/build.js
// https://github.com/shelljs/shelljs
// 檢查NodeJS和npm的版本
require('./check-versions')()
process.env.NODE_ENV = 'production'
// Elegant terminal spinner
var ora = require('ora')
var path = require('path')
// 用於在控制檯輸出帶顏色字體的插件
var chalk = require('chalk')
// 執行Unix命令行的插件
var shell = require('shelljs')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
var spinner = ora('building for production...')
spinner.start() // 開啓loading動畫
// 輸出文件的目標文件夾
var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)
// 遞歸刪除舊的目標文件夾
shell.rm('-rf', assetsPath)
// 重新創建文件夾
shell.mkdir('-p', assetsPath)
shell.config.silent = true
// 將static文件夾複製到輸出的目標文件夾
shell.cp('-R', 'static/*', assetsPath)
shell.config.silent = false
// webpack編譯
webpack(webpackConfig, function (err, stats) {
spinner.stop() // 停止loading動畫
if (err) throw err
// 沒有出錯則輸出相關信息
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
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'
))
})
5.build/webpack.prod.conf.js (npm run build用到的配置文件)
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
// 用於從webpack生成的bundle中提取文本到特定文件中的插件
// 可以抽取出css,js文件將其與webpack輸出的bundle分離
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: config.build.env
// 合併基礎的webpack配置
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
// 配置webpack的輸出
output: {
// 編譯輸出目錄
path: config.build.assetsRoot,
// 編譯輸出文件名格式
filename: utils.assetsPath('js/[name].[chunkhash].js'),
// 沒有指定輸出名的文件輸出的文件名格式
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
// 配置webpack插件
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
// 醜化壓縮代碼
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// 抽離css文件
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// 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'
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// 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',
chunks: ['vendor']
})
]
})
// gzip模式下需要引入compression插件進行壓縮
if (config.build.productionGzip) {
var 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) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
6.config/index.js
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
// 構建產品時使用的配置
build: {
// webpack的編譯環境
env: require('./prod.env'),
// 編譯輸入的index.html文件
index: path.resolve(__dirname, '../dist/index.html'),
// webpack輸出的目標文件夾路徑
assetsRoot: path.resolve(__dirname, '../dist'),
// webpack編譯輸出的二級文件夾
assetsSubDirectory: 'static',
// webpack編譯輸出的發佈路徑
assetsPublicPath: '/',
// 使用SourceMap
productionSourceMap: true,
// 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
// 默認不打開開啓gzip模式
productionGzip: false,
// gzip模式下需要壓縮的文件的擴展名
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
bundleAnalyzerReport: process.env.npm_config_report
},
// 開發過程中使用的配置
dev: {
// webpack的編譯環境
env: require('./dev.env'),
// dev-server監聽的端口
port: 8080,
// 啓動dev-server之後自動打開瀏覽器
autoOpenBrowser: true,
// webpack編譯輸出的二級文件夾
assetsSubDirectory: 'static',
// webpack編譯輸出的發佈路徑
assetsPublicPath: '/',
// 請求代理表,在這裏可以配置特定的請求代理到對應的API接口
// 例如將'/api/xxx'代理到'www.example.com/api/xxx'
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
// 是否開啓 cssSourceMap
cssSourceMap: false
}
}
以上配置的配置文件內容摘抄自:http://blog.csdn.net/hongchh/article/details/55113751
在使用npm run build進行webpack打包後,發佈的項目可能會遇到圖片等找不到的情況。
這裏有一個萬能解決辦法:
1. 將config/index.js 裏面的 assetsPublicPath:'/' 改爲assetsPublicPath:'./'
2. build/util.js裏面的
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader',
publicPath:'/'
})
將其中的publicPath改爲:publicPath:'../../'就可以了。這樣打包出來的路徑就是正確的了。
第一個是爲了改變js中引入圖片的路徑,改爲./ 就是指在當前路徑,這個.代表的路徑就是assetsRoot+assetsSubDictionary,我這裏定位到dist/static/ ,加上圖片前綴img,就可以找到了。
第二種是爲了改變vue文件中使用style樣式裏面例如background:url('xxx'),這樣的路徑,因爲style最終變成css文件在dist/static/css裏面,我們的圖片放在dist/static/img中,那麼加上../../變成dist目錄下,默認的目錄前綴是static,img是圖片默認前綴,這樣就可以定位到圖片。