vue項目結構
├── build --------------------------------- webpack相關配置文件 css
│ ├── build.js --------------------------webpack打包配置文件 html
│ ├── check-versions.js ------------------------------ 檢查npm,nodejs版本 vue
│ ├── dev-client.js ---------------------------------- 設置環境 node
│ ├── dev-server.js ---------------------------------- 建立express服務器,配置中間件,啓動可熱重載的服務器,用於開發項目 webpack
│ ├── utils.js --------------------------------------- 配置資源路徑,配置css加載器 git
│ ├── vue-loader.conf.js ----------------------------- 配置css加載器等 github
│ ├── webpack.base.conf.js --------------------------- webpack基本配置 web
│ ├── webpack.dev.conf.js ---------------------------- 用於開發的webpack設置 express
│ ├── webpack.prod.conf.js --------------------------- 用於打包的webpack設置 npm
├── config ---------------------------------- 配置文件
├── node_modules ---------------------------- 存放依賴的目錄
├── src ------------------------------------- 源碼
│ ├── assets ------------------------------ 靜態文件
│ ├── components -------------------------- 組件
│ ├── main.js ----------------------------- 主js
│ ├── App.vue ----------------------------- 項目入口組件
│ ├── router ------------------------------ 路由
├── package.json ---------------------------- node配置文件
├── .babelrc--------------------------------- babel配置文件
├── .editorconfig---------------------------- 編輯器配置
├── .gitignore------------------------------- 配置git可忽略的文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
主要的配置文件
首選來看一下package.json裏面scripts字段,看一下在執行npm run dev 和npm run build時作了什麼
"name": "laoli",
"version": "1.0.0",
"description": "aaa",
"scripts": {
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"build": "node build/build.js"
}
1
2
3
4
5
6
7
8
當咱們執行npm run dev時,首選執行的是dev-server.js
當咱們執行npm run build時,首選執行的是build.js
dev-server.js
引入配置文件
引入相關插件
建立express實例
配置webpack-dev-middleware和webpack-hot-middleware
配置靜態資源路徑,並掛到express服務上
啓動服務器,並判斷是否自動打開默認瀏覽器
監聽端口
require('./check-versions')()
//引入相關配置
var config = require('../config')
// 檢查Node的環境變量,若是沒有則使用配置文件中設置的環境
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
//opn -- A better node-open. Opens stuff like websites, files, executables. Cross-platform.
//這裏用來打開默認瀏覽器,打開dev-server監聽的端口
var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
//express中間件,用於http請求代理到其餘服務器
var proxyMiddleware = require('http-proxy-middleware')
//判斷當前環境,選擇導入的webpack配置
var webpackConfig = process.env.NODE_ENV === 'testing'
? require('./webpack.prod.conf')
require('./webpack.dev.conf')
// default port where dev server listens for incoming traffic
//默認的dev-server的監聽端口
var port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
//是否自動打開瀏覽器,默認是false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
//定義http代理到你的自定義的API後端
var proxyTable = config.dev.proxyTable
//建立express實例
var app = express()
// 根據webpack的config建立Compiler對象
var compiler = webpack(webpackConfig)
//使用compiler相應的文件進行編譯和綁定,編譯後的內容將存放在內存中
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
//用於實現熱重載
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: false,
heartbeat: 2000
})
// force page reload when html-webpack-plugin template changes
//當html-webpack-plugin提交頁面以後,使用熱重載強制頁面重載
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// proxy api requests
//在express上使用代理表中的配置
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
// handle fallback for HTML5 history API
//一個解決單頁的重定向錯誤的插件
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
// 使用devMiddleware,webpack編譯後的文件將掛到express服務器上
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
// 使用熱重載中間件
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'))
//設置應用的url
var uri = 'http://localhost:' + port
var _resolve
var readyPromise = new Promise(resolve => {
_resolve = resolve
})
console.log('> Starting dev server...')
//devMiddleware valid以後,啓動服務
devMiddleware.waitUntilValid(() => {
console.log('> Listening at ' + uri + '\n')
// when env is testing, don't need open it
//若是設置爲自動打開瀏覽器,經過opn打開uri
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri)
}
_resolve()
})
//監聽配置的端口
var server = app.listen(port)
module.exports = {
ready: readyPromise,
close: () => {
server.close()
}
}
1
2
3
4
5
6
7
8
webpack.base.conf.js
配置編譯入口和輸出路徑
模塊resolve的規則
配置不一樣類型模塊的處理規則
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
//絕對路徑
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
//webpack的入口文件
entry: {
app: './src/main.js'
},
output: {
//webpack輸出文件的路徑
path: config.build.assetsRoot,
//輸出的文件命名格式
filename: '[name].js',
// webpack編譯輸出的發佈路徑
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
//模塊resolve的規則
resolve: {
//resolve的後綴名
extensions: ['.js', '.vue', '.json'],
//配置路徑別名,好比import Vue from 'vue/dist/vue.common.js'--> import Vue from 'vue'
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src')
}
},
//配置不一樣類型模塊的處理規則
module: {
rules: [
// src和test文件夾下的.js和.vue文件使用eslint-loader
{
test: /.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
//全部的.vue文件使用vue-loader
{
test: /.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
//src和test下的.js文件使用babel-loader
{
test: /.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
//全部的圖片文件使用url-loader
{
test: /.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
//全部的音頻文件使用url-loader
{
test: /.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
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]')
}
}
]
}
}
1
2
3
4
5
6
7
8
9
webpack.dev.conf.js
合併基礎的webpack配置
使用styleLoaders
配置Source Maps
配置webpack插件
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
//生成html文件並自動注入依賴文件的插件, script & link
var HtmlWebpackPlugin = require('html-webpack-plugin')
//一個輸出webpack警告,錯誤的插件
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
//添加熱重載相關的代碼到entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
//合併webpack.base.conf
module.exports = merge(baseWebpackConfig, {
module: {
//使用styleLoaders處理樣式文件
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// cheap-module-eval-source-map is faster for development
//配置Source Maps
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(),
//在編譯出現錯誤時,使用 NoEmitOnErrorsPlugin 來跳過輸出階段。這樣能夠確保輸出資源不會包含錯誤。
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
})
1
2
3
4
5
6
7
8
9
10
** 配置Source Maps
source-map 在一個單獨的文件中產生一個完整且功能徹底的文件。這個文件具備最好的sourcemap,可是它會減慢打包文件的構建速度;
cheap-module-source-map在一個單獨的文件中生成一個不帶列映射的map,不帶列映射提升項目構建速度,可是也使得瀏覽器開發者工具只能對應到具體的行,不能對應到具體的列(符號),會對調試形成不便;
eval-source-map 使用eval打包源文件模塊,在同一個文件中生成乾淨的完整的sourcemap。這個選項能夠在不影響構建速度的前提下生成完整的sourcemap,可是對打包後輸出的JS文件的執行具備性能和安全的隱患。不過在開發階段這是一個很是好的選項,可是在生產階段必定不要用這個選項;
cheap-module-eval-source-map 這是在打包文件時最快的生成source map的方法,生成的SourceMap 會和打包後的JavaScript文件同行顯示,沒有列映射,和eval-source-map選項具備類似的缺點;
build.js
webpack編譯
輸出信息
require('./check-versions')()
process.env.NODE_ENV = 'production'
//控制檯loading動畫
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
// 高亮控制檯輸出的插件
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
//在控制檯輸出building for production...
var spinner = ora('building for production...')
//開始loading動畫
spinner.start()
//獲取輸出文件路徑
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
//webpack編譯
webpack(webpackConfig, function (err, stats) {
//中止loading動畫
spinner.stop()
//若是錯誤拋出錯誤
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'
))
})
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
webpack.prod.conf.js
合併基礎的webpack配置
配置webpack的輸出
配置webpack插件
配置gzip模式
配置webpack-bundle-analyzer,分析打包後生成的文件結構
var env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
config.build.env
//合併webpack.base.conf
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
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 webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// extract css into its own file
//從bundle中抽取css文件
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
//壓縮抽取的css文件
new OptimizeCSSPlugin({
cssProcessorOptions: {
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
//用於生成dist/index.html,加入hash用於緩存。hash不改變不進行更新
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
//分離第三方js到單獨的文件中
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']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
// 配置gzip模式
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
})
)
}
//配置webpack-bundle-analyzer,分析打包後生成的文件結構
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
1
2
config/index.js
最後是config中的index.js文件,它都配置了什麼
var path = require('path')
module.exports = {
//打包時使用的配置
build: {
//webpack的環境
env: require('./prod.env'),
//輸入的index.html的路徑
index: path.resolve(__dirname, '../dist/index.html'),
//輸出的目標文件夾路徑
assetsRoot: path.resolve(__dirname, '../dist'),
//輸出的子文件夾路徑
assetsSubDirectory: 'static',
//發佈路徑
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'),
//端口
port: 8080,
//是否自動打開瀏覽器
autoOpenBrowser: true,
//輸出的子文件夾路徑
assetsSubDirectory: 'static',
//發佈路徑
assetsPublicPath: '/',
//配置代理表
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: false
}
}--------------------- 原文:https://blog.csdn.net/qq_39542027/article/details/80002461