当我们需要和后台分离部署的时候,必须配置config/index.js:

用vue-cli 自动构建的目录里面  (环境变量及其基本变量的配置)

var path = require('path')

module.exports = {
build: {
index: path.resolve(__dirname, 'dist/index.html'),
assetsRoot: path.resolve(__dirname, 'dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true
},
dev: {
port: 8080,
proxyTable: {}
}
}

在'build'部分,我们有以下选项:

build.index

必须是本地文件系统上的绝对路径。

index.html (带着插入的资源路径) 会被生成。

如果你在后台框架中使用此模板,你可以编辑index.html路径指定到你的后台程序生成的文件。例如Rails程序,可以是app/views/layouts/application.html.erb,或者Laravel程序,可以是resources/views/index.blade.php

build.assetsRoot

必须是本地文件系统上的绝对路径。

应该指向包含应用程序的所有静态资产的根目录。public/ 对应Rails/Laravel。

build.assetsSubDirectory

被webpack编译处理过的资源文件都会在这个build.assetsRoot目录下,所以它不可以混有其它可能在build.assetsRoot里面有的文件。例如,假如build.assetsRoot参数是/path/to/distbuild.assetsSubDirectory 参数是 static, 那么所以webpack资源会被编译到path/to/dist/static目录。

每次编译前,这个目录会被清空,所以这个只能放编译出来的资源文件。

static/目录的文件会直接被在构建过程中,直接拷贝到这个目录。这意味着是如果你改变这个规则,所有你依赖于static/中文件的绝对地址,都需要改变。

build.assetsPublicPath【资源的根目录】

这个是通过http服务器运行的url路径。在大多数情况下,这个是根目录(/)。如果你的后台框架对静态资源url前缀要求,你仅需要改变这个参数。在内部,这个是被webpack当做output.publicPath来处理的。

后台有要求的话一般要加上./ 或者根据具体目录添加,不然引用不到静态资源

build.productionSourceMap

在构建生产环境版本时是否开启source map。

dev.port

开发服务器监听的特定端口

dev.proxyTable

定义开发服务器的代理规则。

项目中配置的config/index.js,有dev和production两种环境的配置 以下介绍的是production环境下的webpack配置的理解

var path = require('path')

module.exports = {
build: { // production 环境
env: require('./prod.env'), // 使用 config/prod.env.js 中定义的编译环境
index: path.resolve(__dirname, '../dist/index.html'), // 编译输入的 index.html 文件
assetsRoot: path.resolve(__dirname, '../dist'), // 编译输出的静态资源路径
assetsSubDirectory: 'static', // 编译输出的二级目录
assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名
productionSourceMap: true, // 是否开启 cssSourceMap
// 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
productionGzip: false, // 是否开启 gzip
productionGzipExtensions: ['js', 'css'] // 需要使用 gzip 压缩的文件扩展名
},
dev: { // dev 环境
env: require('./dev.env'), // 使用 config/dev.env.js 中定义的编译环境
port: 8080, // 运行测试页面的端口
assetsSubDirectory: 'static', // 编译输出的二级目录
assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名
proxyTable: {}, // 需要 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 // 是否开启 cssSourceMap
}
}

下面是vue中的build/webpack.base.conf.js

//引入依赖模块
var path = require('path')
var config = require('../config') // 获取配置
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../') var env = process.env.NODE_ENV
// check env & config/index.js to decide weither to enable CSS Sourcemaps for the
// various preprocessor loaders added to vue-loader at the end of this file
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)/* 是否在 dev 环境下开启 cssSourceMap ,在 config/index.js 中可配置 */
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)/* 是否在 production 环境下开启 cssSourceMap ,在 config/index.js 中可配置 */
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd /* 最终是否使用 cssSourceMap */ module.exports = {
entry: { // 配置webpack编译入口
app: './src/main.js'
},
output: { // 配置webpack输出路径和命名规则
path: config.build.assetsRoot, // webpack输出的目标文件夹路径(例如:/dist)
publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath, // webpack编译输出的发布路径(判断是正式环境或者开发环境等)
filename: '[name].js' // webpack输出bundle文件命名格式,基于文件的md5生成Hash名称的script来防止缓存
},
resolve: {
extensions: ['', '.js', '.vue', '.scss'], //自动解析确定的拓展名,使导入模块时不带拓展名
fallback: [path.join(__dirname, '../node_modules')],
alias: { // 创建import或require的别名,一些常用的,路径长的都可以用别名
'vue$': 'vue/dist/vue',
'src': path.resolve(__dirname, '../src'),
'assets': path.resolve(__dirname, '../src/assets'),
'components': path.resolve(__dirname, '../src/components'),
'scss_vars': path.resolve(__dirname, '../src/styles/vars.scss')
}
},
resolveLoader: {
fallback: [path.join(__dirname, '../node_modules')]
},
module: {
loaders: [
{
test: /\.vue$/, // vue文件后缀
loader: 'vue' //使用vue-loader处理
},
{
test: /\.js$/,
loader: 'babel',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
vue: { // .vue 文件配置 loader 及工具 (autoprefixer)
loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }), //// 调用cssLoaders方法返回各类型的样式对象(css: loader)
postcss: [
require('autoprefixer')({
browsers: ['last 2 versions']
})
]
}
}

webpack.prod.conf.js 生产环境下的配置文件

var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')// 一个可以合并数组和对象的插件
var baseWebpackConfig = require('./webpack.base.conf')
// 用于从webpack生成的bundle中提取文本到特定文件中的插件
// 可以抽取出css,js文件将其与webpack输出的bundle分离
var ExtractTextPlugin = require('extract-text-webpack-plugin') //如果我们想用webpack打包成一个文件,css js分离开,需要这个插件
var HtmlWebpackPlugin = require('html-webpack-plugin')// 一个用于生成HTML文件并自动注入依赖文件(link/script)的webpack插件
var env = config.build.env
// 合并基础的webpack配置
var webpackConfig = merge(baseWebpackConfig, {
// 配置样式文件的处理规则,使用styleLoaders
module: {
loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
},
devtool: config.build.productionSourceMap ? '#source-map' : false, // 开启source-map,生产环境下推荐使用cheap-source-map或source-map,后者得到的.map文件体积比较大,但是能够完全还原以前的js代码
output: {
path: config.build.assetsRoot,// 编译输出目录
filename: utils.assetsPath('js/[name].[chunkhash].js'), // 编译输出文件名格式
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') // 没有指定输出名的文件输出的文件名格式
},
vue: { // vue里的css也要单独提取出来
loaders: utils.cssLoaders({ // css加载器,调用了utils文件中的cssLoaders方法,用来返回针对各类型的样式文件的处理方式,
sourceMap: config.build.productionSourceMap,
extract: true
})
},
// 重新配置插件项
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
// 位于开发环境下
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.optimize.UglifyJsPlugin({// 丑化压缩代码
compress: {
warnings: false
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
// extract css into its own file
new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')), // 抽离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
// filename 生成网页的HTML名字,可以使用/来控制文件文件的目录结构,最
// 终生成的路径是基于webpac配置的output.path的
new HtmlWebpackPlugin({
// 生成html文件的名字,路径和生产环境下的不同,要与修改后的publickPath相结合,否则开启服务器后页面空白
filename: config.build.index,
// 源文件,路径相对于本文件所在的位置
template: 'index.html',
inject: true,// 要把<script>标签插入到页面哪个标签里(body|true|head|false)
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'
}),
// 如果文件是多入口的文件,可能存在,重复代码,把公共代码提取出来,又不会重复下载公共代码了
// (多个页面间会共享此文件的缓存)
// CommonsChunkPlugin的初始化常用参数有解析?
// name: 这个给公共代码的chunk唯一的标识
// filename,如何命名打包后生产的js文件,也是可以用上[name]、[hash]、[chunkhash]
// minChunks,公共代码的判断标准:某个js模块被多少个chunk加载了才算是公共代码
// 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({ // 为组件分配ID,通过这个插件webpack可以分析和优先考虑使用最多的模块,并为它们分配最小的ID
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
})
)
} module.exports = webpackConfig

vue 中build/build.js页面

// https://github.com/shelljs/shelljs
require('./check-versions')() // 检查 Node 和 npm 版本
require('shelljs/global') // 使用了 shelljs 插件,可以让我们在 node 环境的 js 中使用 shell
env.NODE_ENV = 'production' var path = require('path')
var config = require('../config') // 加载 config.js
var ora = require('ora') // 一个很好看的 loading 插件
var webpack = require('webpack') // 加载 webpack
var webpackConfig = require('./webpack.prod.conf') // 加载 webpack.prod.conf console.log( // 输出提示信息 ~ 提示用户请在 http 服务下查看本页面,否则为空白页
' Tip:\n' +
' Built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
) var spinner = ora('building for production...') // 使用 ora 打印出 loading + log
spinner.start() // 开始 loading 动画 /* 拼接编译输出文件路径 */
var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)
rm('-rf', assetsPath) /* 删除这个文件夹 (递归删除) */
mkdir('-p', assetsPath) /* 创建此文件夹 */
cp('-R', 'static/*', assetsPath) /* 复制 static 文件夹到我们的编译输出目录 */ webpack(webpackConfig, function (err, stats) { // 开始 webpack 的编译
// 编译成功的回调函数
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n')
})

项目入口,由package.json 文件可以看出

"scripts": {
"dev": "node build/dev-server.js",
"build": "node build/build.js",
"watch": "node build/build-watch.js"
},

 当我们执行 npm run dev / npm run build  / npm run watch时运行的是 node build/dev-server.js 或 node build/build.js 或node build/build-watch.js

node build/build-watch.js 是我配置的载production环境的配置基础上在webpack的配置模块加上 watch:true  便可实现代码的实时编译

当我们需要和后台分离部署的时候,必须配置config/index.js:

用vue-cli 自动构建的目录里面  (环境变量及其基本变量的配置)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var path = require('path')
 
module.exports = {
  build: {
    index: path.resolve(__dirname, 'dist/index.html'),
    assetsRoot: path.resolve(__dirname, 'dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: true
  },
  dev: {
    port: 8080,
    proxyTable: {}
  }
}

  

在'build'部分,我们有以下选项:

build.index

必须是本地文件系统上的绝对路径。

index.html (带着插入的资源路径) 会被生成。

如果你在后台框架中使用此模板,你可以编辑index.html路径指定到你的后台程序生成的文件。例如Rails程序,可以是app/views/layouts/application.html.erb,或者Laravel程序,可以是resources/views/index.blade.php

build.assetsRoot

必须是本地文件系统上的绝对路径。

应该指向包含应用程序的所有静态资产的根目录。public/ 对应Rails/Laravel。

build.assetsSubDirectory

被webpack编译处理过的资源文件都会在这个build.assetsRoot目录下,所以它不可以混有其它可能在build.assetsRoot里面有的文件。例如,假如build.assetsRoot参数是/path/to/distbuild.assetsSubDirectory 参数是 static, 那么所以webpack资源会被编译到path/to/dist/static目录。

每次编译前,这个目录会被清空,所以这个只能放编译出来的资源文件。

static/目录的文件会直接被在构建过程中,直接拷贝到这个目录。这意味着是如果你改变这个规则,所有你依赖于static/中文件的绝对地址,都需要改变。

build.assetsPublicPath【资源的根目录】

这个是通过http服务器运行的url路径。在大多数情况下,这个是根目录(/)。如果你的后台框架对静态资源url前缀要求,你仅需要改变这个参数。在内部,这个是被webpack当做output.publicPath来处理的。

后台有要求的话一般要加上./ 或者根据具体目录添加,不然引用不到静态资源

build.productionSourceMap

在构建生产环境版本时是否开启source map。

dev.port

开发服务器监听的特定端口

dev.proxyTable

定义开发服务器的代理规则。

项目中配置的config/index.js,有dev和production两种环境的配置 以下介绍的是production环境下的webpack配置的理解

 1 var path = require('path')
2
3 module.exports = {
4 build: { // production 环境
5 env: require('./prod.env'), // 使用 config/prod.env.js 中定义的编译环境
6 index: path.resolve(__dirname, '../dist/index.html'), // 编译输入的 index.html 文件
7 assetsRoot: path.resolve(__dirname, '../dist'), // 编译输出的静态资源路径
8 assetsSubDirectory: 'static', // 编译输出的二级目录
9 assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名
10 productionSourceMap: true, // 是否开启 cssSourceMap
11 // Gzip off by default as many popular static hosts such as
12 // Surge or Netlify already gzip all static assets for you.
13 // Before setting to `true`, make sure to:
14 // npm install --save-dev compression-webpack-plugin
15 productionGzip: false, // 是否开启 gzip
16 productionGzipExtensions: ['js', 'css'] // 需要使用 gzip 压缩的文件扩展名
17 },
18 dev: { // dev 环境
19 env: require('./dev.env'), // 使用 config/dev.env.js 中定义的编译环境
20 port: 8080, // 运行测试页面的端口
21 assetsSubDirectory: 'static', // 编译输出的二级目录
22 assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名
23 proxyTable: {}, // 需要 proxyTable 代理的接口(可跨域)
24 // CSS Sourcemaps off by default because relative paths are "buggy"
25 // with this option, according to the CSS-Loader README
26 // (https://github.com/webpack/css-loader#sourcemaps)
27 // In our experience, they generally work as expected,
28 // just be aware of this issue when enabling this option.
29 cssSourceMap: false // 是否开启 cssSourceMap
30 }
31 }

下面是vue中的build/webpack.base.conf.js

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//引入依赖模块
var path = require('path')
var config = require('../config'// 获取配置
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')
 
var env = process.env.NODE_ENV
// check env & config/index.js to decide weither to enable CSS Sourcemaps for the
// various preprocessor loaders added to vue-loader at the end of this file
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)/* 是否在 dev 环境下开启 cssSourceMap ,在 config/index.js 中可配置 */
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)/* 是否在 production 环境下开启 cssSourceMap ,在 config/index.js 中可配置 */
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd /* 最终是否使用 cssSourceMap */
 
module.exports = {
  entry: {   // 配置webpack编译入口
    app: './src/main.js' 
  },
  output: {    // 配置webpack输出路径和命名规则
    path: config.build.assetsRoot, // webpack输出的目标文件夹路径(例如:/dist)
    publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,  // webpack编译输出的发布路径(判断是正式环境或者开发环境等)
    filename: '[name].js'   // webpack输出bundle文件命名格式,基于文件的md5生成Hash名称的script来防止缓存
  },
  resolve: {
    extensions: ['''.js''.vue''.scss'],  //自动解析确定的拓展名,使导入模块时不带拓展名
    fallback: [path.join(__dirname, '../node_modules')],
    alias: {  // 创建import或require的别名,一些常用的,路径长的都可以用别名
      'vue$''vue/dist/vue',
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components'),
      'scss_vars': path.resolve(__dirname, '../src/styles/vars.scss')
    }
  },
  resolveLoader: {
    fallback: [path.join(__dirname, '../node_modules')]
  },
  module: {
    loaders: [
        {
            test: /\.vue$/, // vue文件后缀
            loader: 'vue'   //使用vue-loader处理
        },
        {
            test: /\.js$/,
            loader: 'babel',
            include: projectRoot,
            exclude: /node_modules/
        },
        {
            test: /\.json$/,
            loader: 'json'
        },
        {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url',
            query: {
              limit: 10000,
              name: utils.assetsPath('img/[name].[hash:7].[ext]')
            }
        },
        {
            test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
            loader: 'url',
            query: {
              limit: 10000,
              name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
            }
        }
    ]
  },
  vue: {    // .vue 文件配置 loader 及工具 (autoprefixer)
    loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }), //// 调用cssLoaders方法返回各类型的样式对象(css: loader)
    postcss: [
      require('autoprefixer')({
        browsers: ['last 2 versions']
      })
    ]
  }
}

  webpack.prod.conf.js 生产环境下的配置文件

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')// 一个可以合并数组和对象的插件
var baseWebpackConfig = require('./webpack.base.conf')
// 用于从webpack生成的bundle中提取文本到特定文件中的插件
// 可以抽取出css,js文件将其与webpack输出的bundle分离
var ExtractTextPlugin = require('extract-text-webpack-plugin')  //如果我们想用webpack打包成一个文件,css js分离开,需要这个插件
var HtmlWebpackPlugin = require('html-webpack-plugin')// 一个用于生成HTML文件并自动注入依赖文件(link/script)的webpack插件
var env = config.build.env
// 合并基础的webpack配置
var webpackConfig = merge(baseWebpackConfig, {
    // 配置样式文件的处理规则,使用styleLoaders
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
  },
  devtool: config.build.productionSourceMap ? '#source-map' false// 开启source-map,生产环境下推荐使用cheap-source-map或source-map,后者得到的.map文件体积比较大,但是能够完全还原以前的js代码
  output: {
    path: config.build.assetsRoot,// 编译输出目录
    filename: utils.assetsPath('js/[name].[chunkhash].js'),  // 编译输出文件名格式
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')  // 没有指定输出名的文件输出的文件名格式
  },
  vue: { // vue里的css也要单独提取出来
    loaders: utils.cssLoaders({ // css加载器,调用了utils文件中的cssLoaders方法,用来返回针对各类型的样式文件的处理方式,
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  // 重新配置插件项
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    // 位于开发环境下
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({// 丑化压缩代码
      compress: {
        warnings: false
      }
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    // extract css into its own file
    new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),  // 抽离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
     // filename 生成网页的HTML名字,可以使用/来控制文件文件的目录结构,最
      // 终生成的路径是基于webpac配置的output.path的
    new HtmlWebpackPlugin({
        // 生成html文件的名字,路径和生产环境下的不同,要与修改后的publickPath相结合,否则开启服务器后页面空白
      filename: config.build.index,
      // 源文件,路径相对于本文件所在的位置
      template: 'index.html',
      inject: true,// 要把<script>标签插入到页面哪个标签里(body|true|head|false)
      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'
    }),
    // 如果文件是多入口的文件,可能存在,重复代码,把公共代码提取出来,又不会重复下载公共代码了
    // (多个页面间会共享此文件的缓存)
    // CommonsChunkPlugin的初始化常用参数有解析?
    // name: 这个给公共代码的chunk唯一的标识
    // filename,如何命名打包后生产的js文件,也是可以用上[name]、[hash]、[chunkhash]
    // minChunks,公共代码的判断标准:某个js模块被多少个chunk加载了才算是公共代码
    // 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({ // 为组件分配ID,通过这个插件webpack可以分析和优先考虑使用最多的模块,并为它们分配最小的ID
      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
    })
  )
}
 
module.exports = webpackConfig

  

vue 中build/build.js页面

 1 // https://github.com/shelljs/shelljs
2 require('./check-versions')() // 检查 Node 和 npm 版本
3 require('shelljs/global') // 使用了 shelljs 插件,可以让我们在 node 环境的 js 中使用 shell
4 env.NODE_ENV = 'production'
5
6 var path = require('path')
7 var config = require('../config') // 加载 config.js
8 var ora = require('ora') // 一个很好看的 loading 插件
9 var webpack = require('webpack') // 加载 webpack
10 var webpackConfig = require('./webpack.prod.conf') // 加载 webpack.prod.conf
11
12 console.log( // 输出提示信息 ~ 提示用户请在 http 服务下查看本页面,否则为空白页
13 ' Tip:\n' +
14 ' Built files are meant to be served over an HTTP server.\n' +
15 ' Opening index.html over file:// won\'t work.\n'
16 )
17
18 var spinner = ora('building for production...') // 使用 ora 打印出 loading + log
19 spinner.start() // 开始 loading 动画
20
21 /* 拼接编译输出文件路径 */
22 var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)
23 rm('-rf', assetsPath) /* 删除这个文件夹 (递归删除) */
24 mkdir('-p', assetsPath) /* 创建此文件夹 */
25 cp('-R', 'static/*', assetsPath) /* 复制 static 文件夹到我们的编译输出目录 */
26
27 webpack(webpackConfig, function (err, stats) { // 开始 webpack 的编译
28 // 编译成功的回调函数
29 spinner.stop()
30 if (err) throw err
31 process.stdout.write(stats.toString({
32 colors: true,
33 modules: false,
34 children: false,
35 chunks: false,
36 chunkModules: false
37 }) + '\n')
38 })

项目入口,由package.json 文件可以看出

1
2
3
4
5
"scripts": {
    "dev""node build/dev-server.js",
    "build""node build/build.js",
    "watch""node build/build-watch.js"
  },

  当我们执行 npm run dev / npm run build  / npm run watch时运行的是 node build/dev-server.js 或 node build/build.js 或node build/build-watch.js

node build/build-watch.js 是我配置的载production环境的配置基础上在webpack的配置模块加上 watch:true  便可实现代码的实时编译

vue中webpack的配置理解的更多相关文章

  1. axios在vue中的简单配置与使用

    一.axios 简介 axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:https://hzzly.github.io/2017/03/12/ ...

  2. Vue中diff算法的理解

    Vue中diff算法的理解 diff算法用来计算出Virtual DOM中改变的部分,然后针对该部分进行DOM操作,而不用重新渲染整个页面,渲染整个DOM结构的过程中开销是很大的,需要浏览器对DOM结 ...

  3. cli中webpack的配置详解

    一.前言 vue-cli是构建vue单页应用的脚手架,输入一串指定的命令行从而自动生成vue.js+wepack的项目模板.这其中webpack发挥了很大的作用,它使得我们的代码模块化,引入一些插件帮 ...

  4. vue 一些webpack的配置详解

    最近一直在忙着做项目 本来想养成一个经常跟新博客的习惯 , 但是实在是太难了 , 每天加班到10点多 .8点能下班都是最好的了 , 小公司真不好待呀 分享一下最近半年的vue心得吧 我的项目是在他的基 ...

  5. Vue中keep-alive组件的理解

    对keep-alive组件的理解 当在组件之间切换的时候,有时会想保持这些组件的状态,以避免反复重渲染导致的性能等问题,使用<keep-alive>包裹动态组件时,会缓存不活动的组件实例, ...

  6. vue中的插槽slot理解

    本篇文章参考赛冷思的个人博客 1.函数默认传参 在我们写js函数我们的可能会给他们一个默认的参数,写法是 function show(age,name){ var age = age || 20; v ...

  7. vue中mixin的一点理解

    vue中提供了一种混合机制--mixins,用来更高效的实现组件内容的复用.最开始我一度认为这个和组件好像没啥区别..后来发现错了.下面我们来看看mixins和普通情况下引入组件有什么区别?     ...

  8. vue中eslintrc.js配置最详细介绍

    本文是对vue项目中自带文件eslintrc.js的内容解析, 介绍了各个eslint配置项的作用,以及为什么这样设置. 比较详细,看完能对eslint有较为全面的了解,基本解除对该文件的疑惑. /* ...

  9. vue中的config配置

    在webpack.base.conf文件中配置别名以及扩展名 resolve: { extensions: ['.js', '.vue', '.json', '.styl'], alias: { 'v ...

随机推荐

  1. excel制作田字格,excel行高磅,列宽1/10英寸;

    打开一个excel表格,发现列宽是行高的4倍: 开始-格式中查看,发现行高14.25磅,列宽8.38*1/10英寸: 网上百度,了解1英寸=72磅: 那么列宽8.38=60.336磅: 60.336英 ...

  2. 使用响应的json数据判断订单查询是否成功;

    #查询中通快递import requestsrr=requests.session()headers={"User-Agent": "Mozilla/5.0 (Windo ...

  3. pugixml的简单使用

    一.简介 pugixml的官方主页为:http://pugixml.org/ pugixml是一个很棒的XML操作库, 它很轻量,只有三个文件(pugiconfig.hpp   pugixml.cpp ...

  4. 鱼嘤嘤小分队 Alpha冲刺阶段博客目录

    会议记录 周数 链接 主要工作 第六周 第六周链接  确定技术路线 第七周 第七周链接  讨论进展 最近的主要工作: 由于我们的代码能力以及pyhon的基础知识已经网络通信的知识储备是不够的,所以我们 ...

  5. lua 5 流程控制 if

    条件判断中,0 表示 true,只有 nil 才是 false if(0) then -- 可以没有括号 print("0 为 true") elseif 1 then print ...

  6. IntelliJ IDEA创建一个简单的Java Project(二)

    1.  选择要创建的项目类型,同时配置本地的JDK 2. 是否使用模板创建项目 3. 选择项目在本地的存储位置 4. 点击Finish,完成一个简单的Java工程的创建.

  7. 让人又爱又恨的this

    this是个神奇的东西, 既可以帮助我们把模拟的类实例化. 又可以在事件绑定里准确指向触发元素. 还可以帮助我们在对象方法中操作对象的其他属性或方法. 甚至可以在使用apply.call.bing.f ...

  8. 快速获取 IP 地址

    IP 地址可以分为两类,公用和私有(专用).公用 IP 是唯一的 IP 地址,可以从 Internet 访问.专用 IP 地址保留供您专用网络内部使用,而不会直接暴露给 Internet. 本文将介绍 ...

  9. ESP8266 LUA脚本语言开发: 外设篇-GPIO输出高低电平

    前言 所有的LUA开发API参考 https://nodemcu.readthedocs.io/en/master/en/modules/gpio/ 原理图 让GPIO2输出高电平只需 gpio.mo ...

  10. 快速傅立叶变换(FFT)

    多项式 系数表示法 设\(f(x)\)为一个\(n-1\)次多项式,则 \(f(x)=\sum\limits_{i=0}^{n-1}a_i*x_i\) 其中\(a_i\)为\(f(x)\)的系数,用这 ...