详解 vue-cli 的打包配置文件代码(带注释)

host: ‘c.y.qq.com’

},

params: req.query

}).then((response) => {

res.json(response.data)

}).catch((e) => {

console.log(e)

})

})

apiRoutes.get(‘/lyric’, function (req, res) {

var url = ‘https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg’

axios.get(url, {

headers: {

referer: ‘https://c.y.qq.com/’,

host: ‘c.y.qq.com’

},

params: req.query

}).then((response) => {

var ret = response.data

if (typeof ret === ‘string’) {

var reg = /\w+(({[()]+}))$/

var matches = ret.match(reg)

if (matches) {

ret = JSON.parse(matches[1])

}

}

res.json(ret)

}).catch((e) => {

console.log(e)

})

})

app.use(‘/api’, apiRoutes)

var compiler = webpack(webpackConfig)

// 启动 webpack-dev-middleware,将 编译后的文件暂存到内存中

var devMiddleware = require(‘webpack-dev-middleware’)(compiler, {

publicPath: webpackConfig.output.publicPath,

quiet: true

})

// 启动 webpack-hot-middleware,也就是我们常说的 Hot-reload

var hotMiddleware = require(‘webpack-hot-middleware’)(compiler, {

log: () => {}

})

// force page reload when html-webpack-plugin template changes

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]

if (typeof options === ‘string’) {

options = { target: options }

}

app.use(proxyMiddleware(options.filter || context, options))

})

// 使用 connect-history-api-fallback 匹配资源,如果不匹配就可以重定向到指定地址

app.use(require(‘connect-history-api-fallback’)())

// 将暂存到内存中的 webpack 编译后的文件挂在到 express 服务上

app.use(devMiddleware)

// 将 Hot-reload 挂在到 express 服务上

app.use(hotMiddleware)

// 拼接 static 文件夹的静态资源路径

var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)

// 为静态资源提供响应服务

app.use(staticPath, express.static(‘./static’))

var uri = ‘http://localhost:’ + port

var _resolve

var readyPromise = new Promise(resolve => {

_resolve = resolve

})

console.log(‘> Starting dev server…’)

devMiddleware.waitUntilValid(() => {

console.log('> Listening at ’ + uri + ‘\n’)

// 如果不是测试环境,自动打开浏览器并跳到我们的开发地址

if (autoOpenBrowser && process.env.NODE_ENV !== ‘testing’) {

opn(uri)

}

_resolve()

})

// 让我们这个 express 服务监听 port 的请求,并且将此服务作为 dev-server.js 的接口暴露

var server = app.listen(port)

module.exports = {

ready: readyPromise,

close: () => {

server.close()

}

}

2、build/webpack.base.conf.js

var path = require(‘path’)

var utils = require(‘./utils’)

var config = require(‘…/config’)

// .vue 文件配置 loader 及工具 (autoprefixer)

var vueLoaderConfig = require(‘./vue-loader.conf’)

// 拼接我们的工作区路径为一个绝对路径的函数

function resolve(dir) {

return path.join(__dirname, ‘…’, dir)

}

// webpack 配置,输入、输出、模块、插件

module.exports = {

entry: {

app: ‘./src/main.js’

},

output: {

// 编译输出的根路径

path: config.build.assetsRoot,

// 编译输出的文件名

filename: ‘[name].js’,

// 正式发布环境下编译输出的发布路径

publicPath: process.env.NODE_ENV === ‘production’

? config.build.assetsPublicPath
config.dev.assetsPublicPath

},

resolve: {

// 自动补全的扩展名

extensions: [‘.js’, ‘.vue’, ‘.json’],

// 默认路径代理,即起别名,例如 import Vue from ‘vue’,会自动到 'vue/dist/vue.common.js’中寻找

alias: {

‘@’: resolve(‘src’),

‘common’: resolve(‘src/common’),

‘components’: resolve(‘src/components’),

‘base’: resolve(‘src/base’),

‘api’: resolve(‘src/api’)

}

},

module: {

rules: [

// 需要处理的文件及使用的 loader

{

test: /.(js|vue)$/,

loader: ‘eslint-loader’,

enforce: ‘pre’,

include: [resolve(‘src’), resolve(‘test’)],

options: {

// eslint 代码检查配置工具

formatter: require(‘eslint-friendly-formatter’)

}

},

{

test: /.vue$/,

loader: ‘vue-loader’,

options: vueLoaderConfig

},

{

test: /.js$/,

loader: ‘babel-loader’,

include: [resolve(‘src’), resolve(‘test’)]

},

{

test: /.(png|jpe?g|gif|svg)(?.*)?$/,

loader: ‘url-loader’,

options: {

limit: 10000,

name: utils.assetsPath(‘img/[name].[hash:7].[ext]’)

}

},

{

test: /.(woff2?|eot|ttf|otf)(?.*)?$/,

loader: ‘url-loader’,

options: {

limit: 10000,

name: utils.assetsPath(‘fonts/[name].[hash:7].[ext]’)

}

}

]

}

}

3、build/webpack.dev.conf.js

// 使用一些小工具

var utils = require(‘./utils’)

var webpack = require(‘webpack’)

// 同样的使用了 config/index.js 的预设配置

var config = require(‘…/config’)

// 使用 webpack 配置合并插件

var merge = require(‘webpack-merge’)

// 加载 webpack.base.conf

var baseWebpackConfig = require(‘./webpack.base.conf’)

// 使用 html-webpack-plugin 插件,这个插件可以帮我们自动生成 html 并且注入到 .html 文件中

var HtmlWebpackPlugin = require(‘html-webpack-plugin’)

// 一个友好的错误提示插件

var FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin’)

// 将 Hol-reload 相对路径添加到 webpack.base.conf 的 对应 entry 前

Object.keys(baseWebpackConfig.entry).forEach(function (name) {

baseWebpackConfig.entry[name] = [‘./build/dev-client’].concat(baseWebpackConfig.entry[name])

})

// 将我们 webpack.dev.conf.js 的配置和 webpack.base.conf.js 的配置合并

module.exports = merge(baseWebpackConfig, {

module: {

// 使用 styleLoaders

rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })

},

// 使用 #eval-source-map 模式作为开发工具,此配置可参考 DDFE 往期文章详细了解

devtool: ‘#cheap-module-eval-source-map’,

plugins: [

// definePlugin 接收字符串插入到代码当中, 所以你需要的话可以写上 JS 的字符串

new webpack.DefinePlugin({

‘process.env’: config.dev.env

}),

// definePlugin 接收字符串插入到代码当中, 所以你需要的话可以写上 JS 的字符串

// HotModule 插件在页面进行变更的时候只会重回对应的页面模块,不会重绘整个 html 文件

new webpack.HotModuleReplacementPlugin(),

// 遇到报错,跳过还行,并提示错误信息

new webpack.NoEmitOnErrorsPlugin(),

// 将 index.html 作为入口,注入 html 代码后生成 index.html文件

new HtmlWebpackPlugin({

filename: ‘index.html’,

template: ‘index.html’,

inject: true

}),

// 使用这个插件,更好的输出错误信息

new FriendlyErrorsPlugin()

]

})

4、build/webpack.prod.conf.js

var path = require(‘path’)

var utils = require(‘./utils’)

var webpack = require(‘webpack’)

var config = require(‘…/config’)

// 加载 webpack 配置合并工具

var merge = require(‘webpack-merge’)

// 加载 webpack.base.conf.js文件

var baseWebpackConfig = require(‘./webpack.base.conf’)

var CopyWebpackPlugin = require(‘copy-webpack-plugin’)

// 一个可以插入 html 并且创建新的 .html 文件的插件

var HtmlWebpackPlugin = require(‘html-webpack-plugin’)

// 一个 webpack 扩展,可以提取一些代码并且将它们和文件分离开

// 如果我们想将 webpack 打包成一个文件 css js 分离开,那我们需要这个插件

var ExtractTextPlugin = require(‘extract-text-webpack-plugin’)

var OptimizeCSSPlugin = require(‘optimize-css-assets-webpack-plugin’)

var env = config.build.env

// 合并 webpack.base.conf.js

var webpackConfig = merge(baseWebpackConfig, {

module: {

// 使用的 loader

rules: utils.styleLoaders({

sourceMap: config.build.productionSourceMap,

extract: true

})

},

// 是否使用 #source-map 开发工具,更多信息可以查看 DDFE 往期文章

devtool: config.build.productionSourceMap ? ‘#source-map’ : false,

output: {

// 编译输出目录

path: config.build.assetsRoot,

// 编译输出文件名

// 我们可以在 hash 后加 :6 决定使用几位 hash 值

filename: utils.assetsPath(‘js/[name].[chunkhash].js’),

// 没有指定输出名的文件输出的文件名

chunkFilename: utils.assetsPath(‘js/[id].[chunkhash].js’)

},

plugins: [

// definePlugin 接收字符串插入到代码当中, 所以你需要的话可以写上 JS 的字符串

new webpack.DefinePlugin({

‘process.env’: env

}),

// 压缩 js (同样可以压缩 css)

new webpack.optimize.UglifyJsPlugin({

compress: {

warnings: false

},

sourceMap: true

}),

// 将 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.

new OptimizeCSSPlugin({

cssProcessorOptions: {

safe: true

}

}),

// 输入输出的 .html 文件

new HtmlWebpackPlugin({

filename: config.build.index,

template: ‘index.html’,

// 是否注入 html

inject: true,

// 压缩的方式

minify: {

removeComments: true,

collapseWhitespace: true,

removeAttributeQuotes: true

},

chunksSortMode: ‘dependency’

}),

// 没有指定输出文件名的文件输出的静态文件名

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) &&

最后更多分享:前端字节跳动真题解析

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

x,

template: ‘index.html’,

// 是否注入 html

inject: true,

// 压缩的方式

minify: {

removeComments: true,

collapseWhitespace: true,

removeAttributeQuotes: true

},

chunksSortMode: ‘dependency’

}),

// 没有指定输出文件名的文件输出的静态文件名

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) &&

最后更多分享:前端字节跳动真题解析

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

  • [外链图片转存中…(img-tBldAzXB-1714762082079)]
  • 13
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值