vue项目结构及文件介绍(2) —— build文件夹
build文件夹里面是对 webpack 开发和打包的相关设置,包括入口文件、输出文件、使用的模块等;build.js文件构建环境下的配置:loading动画、删除创建目标文件夹、webpack编译、输出信息'use strict' // js的严格模式require('./check-versions')() // node和npm的版本检查process.env.NODE_ENV...
·
build文件夹
里面是对 webpack 开发和打包的相关设置,包括入口文件、输出文件、使用的模块等;
build.js文件
构建环境下的配置:
loading动画、删除创建目标文件夹、webpack编译、输出信息
'use strict' // js的严格模式
require('./check-versions')() // node和npm的版本检查
process.env.NODE_ENV = 'production' // 设置环境变量为生产环境
// 导进各模块
const ora = require('ora') // loading模块
const rm = require('rimraf')
const path = require('path')
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()
// rm方法删除dist/static文件夹
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err //若删除中有错误则抛出异常并终止程序
webpack(webpackConfig, (err, stats) => { //若没有错误则继续执行,构建webpack
spinner.stop() //结束loading动画
if (err) throw err //若有异常则抛出
process.stdout.write(stats.toString({ //标准输出流,类似于console.log
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'
))
})
})
check-versions.js文件
node和npm的版本检查
'use strict' // js的严格模式
// 导进各模块
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs') // shell.js插件,执行unix系统命令
function exec (cmd) {
// 脚本可以通过child_process模块新建子进程,从而执行Unix系统命令
// 将cmd参数传递的值转换成前后没有空格的字符串,也就是版本号
return require('child_process').execSync(cmd).toString().trim()
}
//声明常量数组,数组内容为有关node相关信息的对象
const versionRequirements = [
{
name: 'node', //对象名称为node
currentVersion: semver.clean(process.version), //使用semver插件,把版本信息转换成规定格式
versionRequirement: packageConfig.engines.node //规定package.json中engines选项的node版本信息
}
]
if (shell.which('npm')) { //which为linux指令,在$path规定的路径下查找符合条件的文件
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'), //调用npm --version命令,并且把参数返回给exec函数获取纯净版本
versionRequirement: packageConfig.engines.npm //规定package.json中engines选项的node版本信息
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
// 如果版本号不符合package.json文件中指定的版本号,就执行warning.push...
// 当前版本号用红色标识,要求版本号用绿色标识
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
//如果为真,则打印提示用户升级新版本
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (let i = 0; i < warnings.length; i++) {
const warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}
utils.js文件
配置静态资源路径;
生成cssLoaders用于加载.vue文件中的样式;
生成styleLoaders用于加载不在.vue文件中的单独存在的样式文件
'use strict'
const path = require('path')
const config = require('../config') // 引入config下的index.js文件
const ExtractTextPlugin = require('extract-text-webpack-plugin') // 一个插件,抽离css样式,防止将样式打包在js中引起样式加载错乱
const packageConfig = require('../package.json')
const packageConfig = require('../package.json')
// 导出assetsPath
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path) // path.join返回绝对路径(在电脑上的实际位置);path.posix.join返回相对路径
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
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) {
return ExtractTextPlugin.extract({
use: loaders,
publicPath:'../../',
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
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)
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')
})
}
}
vue-loader.conf.js文件
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production' // 是否为生产环境
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
loaders: utils.cssLoaders({ // 载入utils中的cssloaders返回配置好的css-loader和vue-style=loader
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled, // 是否开启css资源map
cacheBusting: config.dev.cacheBusting, // 是否开启cacheBusting
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
webpack.base.conf.js文件
基本的webpack配置
配置webpack编译入口
配置webpack输出路径和命名规则
配置模块resolve规则
配置不同类型模块的处理规则
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
const vuxLoader = require('vux-loader')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
let webpackConfig = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
externals:{
'BMap':'BMap',
'BMap_Symbol_SHAPE_POINT': 'BMap_Symbol_SHAPE_POINT'
},
output: {
path: config.build.assetsRoot, // 打包后文件输出路径,config/index.js中build.assetsRoot
filename: '[name].js', // 输出文件名称默认使用原名
publicPath: process.env.NODE_ENV === 'production' // 文件引用路径
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'], // 省略扩展名,也就是说当使用.js .vue .json文件导入可以省略后缀名
alias: {
'vue$': 'vue/dist/vue.esm.js', // $符号指精确匹配,路径和文件名要详细
'@': resolve('src'), // resolve('src') 指的是项目根目录中的src文件夹目录,使用@符号代替
}
},
// 用于解析不同的模块
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader', // 解析.vue文件
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader', // 对js文件使用babel-loader转码,用于解析es6等代码
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] // 指明那些文件夹下的js文件需要使用该loader
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader', // 使用url-loader插件,将图片转为base64格式字符串
options: {
limit: 10000, // 10000个字节以下的文件才用来转为dataUrl
name: utils.assetsPath('img/[name].[hash:7].[ext]') //超过10000字节的图片,就按照制定规则设置生成的图片名称,可以看到用了7位hash码来标记,.ext文件是一种索引式文件系统
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
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'
}
}
module.exports = vuxLoader.merge(webpackConfig,{
plugins:['vux-ui']
})
webpack.dev.conf.js文件
开发环境配置
在base.conf基础进一步完善
将hot-reload相关的代码添加到entry chunks
使用styleLoaders
配置Source Maps
配置webpack插件
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin') // 一个用于生成HTML文件并自动注入依赖文件(link/script)的webpack插件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') // 用于更友好地输出webpack的警告、错误等信息
// 获取port
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
/*
合并基础的webpack配置
第一个参数baseWebpackConfig,是webpack基本配置文件webpack.base.conf.js中的配置
*/
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
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: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true, // 是否启用webpack的模块热替换特性。主要是用于开发过程中
contentBase: false, // since we use CopyWebpackPlugin.
compress: true, // 一切服务是否都启用gzip压缩
host: HOST || config.dev.host, // 指定一个host,默认是localhost。如果有全局host就用全局,否则就用index.js中的设置。
port: PORT || config.dev.port, // 指定端口
open: config.dev.autoOpenBrowser, // 是否在浏览器开启本dev server
overlay: config.dev.errorOverlay // 当有编译器错误时,是否在浏览器中显示全屏覆盖
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable, // 代理:如果你有单独的后端开发服务器api,并且希望在同域名下发送api请求,那么代理某些URL会很有用
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll, // 是否使用轮询
}
},
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({
filename: 'index.html',
template: 'index.html',
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
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)
}
})
})
webpack.prod.conf.js文件
生产环境配置
在base.conf基础进一步完善
合并基础webpack配置
使用styleLoaders
配置webpack输出
配置webpack插件
gzip模式下的webpack插件配置
webpack-bundle分析
'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')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: require('../config/prod.env')
// 合并基础的webpack配置
const webpackConfig = merge(baseWebpackConfig, {
module: {
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') // 没有指定输出名的文件输出的文件名格式
},
// 配置webpack插件
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
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.
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
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'
}),
// 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
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
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
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
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
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
更多推荐
已为社区贡献4条内容
所有评论(0)