1:使用vue-cli脚手架创建webpack项目成功后,需要了解项目目录结构和文件功能

2:文件夹介绍
build文件夹:webpack打包相关配置的文件夹
------build.js文件:webpack打包配置文件
'use strict' // 本文件js使用严格模式
require('./check-versions')() // 检查npm和nodejs版本
process.env.NODE_ENV = 'production' // 设置为生产环境,开发环境时不需要打包文件
const ora = require('ora') // 打包时的loading动画插件
const rm = require('rimraf') // rm -rf命令,用来删除文件和文件夹的,不管文件夹是否为空,都可删除,打包时需要先删除原来的包
const path = require('path') // node自带的文件路径插件
const chalk = require('chalk') // 控制台高亮显示的插件,使提示信息在控制台中显示更明显
const webpack = require('webpack') // webpack插件
const config = require('../config') // 项目配置文件 /config/index.js
const webpackConfig = require('./webpack.prod.conf') // 生产环境webpack打包配置
// 打包中使用ora打印出loading动画和log
const spinner = ora('building for production...')
spinner.start()
// 删除旧包,删除成功后执行回调事件
// rimraf具体可参考:https://www.npmjs.com/package/rimraf
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err // 当删除旧包时出现错误,跑出异常
// 执行webpack打包
webpack(webpackConfig, (err, stats) => {
// 打包结束后执行回调方法
spinner.stop() // 打包结束,停止打包中的动画
if (err) throw err // 出现错误跑出异常
process.stdout.write(stats.toString({ // 打印标准的输出流
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) // 标识失败。0表示成功,非0表示失败
}
// 打包成功时,打印高亮信息
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') // 处理所有node.js模块版本控制问题,具体可参考:https://catonmat.net/nodejs-modules-semver
const packageConfig = require('../package.json') // package.json中的配置信息
const shell = require('shelljs') // node API之上的Unix shell命令,可以在js中使用shell命令,具体可参考:https://github.com/shelljs/shelljs
//创建子进程,执行cmd命令,并返回结果
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
// node版本需求
const versionRequirements = [
{
name: 'node', // node
currentVersion: semver.clean(process.version), // 当前node版本
versionRequirement: packageConfig.engines.node // package.json中配置的node版本需求
}
]
// npm版本需求
if (shell.which('npm')) { // 查询npm是否存在
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'), // 获取当前npm版本
versionRequirement: packageConfig.engines.npm // package.json中配置的npm版本需求
})
}
// 暴露模块
module.exports = function () {
const warnings = [] // 警告信息
// 循环检查当前node和npm版本是否符合package.json中配置的版本
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i] // 需求版本
// 如果当前node和npm版本不符合需求,添加警告信息
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)
}
}
------logo.png图片:vue logo图片
------utils.js文件:vue开发环境的webpack相关配置文件,主要处理css-loder和css-style-loader
'use strict' // js严格模式
const path = require('path') // node自带路径处理插件
const config = require('../config') // 项目配置文件 /config/index.js
const ExtractTextPlugin = require('extract-text-webpack-plugin') // 用来将css提取到单独的css文件中
const packageConfig = require('../package.json') // package.json配置文件信息
// 导出assetsPath路径
// assetsSubDirectory:除了index.html 之外的静态资源要存放的路径
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory // 生产环境
: config.dev.assetsSubDirectory // 开发环境
// 返回一个干净的相对根路径
// path.join和path.posix.join的区别就是,前者返回的是完整的路径,后者返回的是完整路径的相对根路径
// 如果path.join的路径是C:a/a/b/xiangmu/b,那么path.posix.join就是b
return path.posix.join(assetsSubDirectory, _path)
}
// 导出cssLoaders的相关配置
exports.cssLoaders = function (options) {
options = options || {}
// cssLoader的基本配置
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap // 是否开启cssmap,默认是false
}
}
// postcssLoader的基本配置
// postcssLoader 主要是对css进行各种不同的转换和处理,添加各种用来兼容浏览器的css前缀,如:-webkit-,-ms-
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap // 是否开启cssmap,默认是false
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] // 根据是否设置了usePostCSS来定义loaders
// 如果使用了less,sass等,在此处增加相应的loader配置
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)
// 根据是否定义了提取css到一个css文件,在此处进行提取配置
// 个extract是自定义的属性,可以定义在options里面,主要作用就是当配置为true就把文件单独提取,false表示不单独提取,这个可以在使用的时候单独配置
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
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)
// 主要处理import这种方式导入的文件类型的打包,上面的exports.cssLoaders是为这一步服务的
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options) // 生成的各种css文件的loader对象
for (const extension in loaders) {
const loader = loaders[extension] // 把每一种文件的laoder都提取出来
// 把最终的结果都push到output数组中
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
// 导出推送错误信息方法
exports.createNotifierCallback = () => {
// 'node-notifier'是一个跨平台系统通知的页面,当遇到错误时,它能用系统原生的推送方式推送信息
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文件:该文件的主要作用就是处理.vue文件,解析这个文件中的每个语言块(template、script、style),转换成js可用的js模块
'use strict' // js使用严格模式
const utils = require('./utils') // 导入自定义uitis方法,同级目录文件utils.js
const config = require('../config') // 导入项目设置文件,/config/index.js
const isProduction = process.env.NODE_ENV === 'production' // 判断是否为生产环境
// 判断是否生成map文件
const sourceMapEnabled = isProduction
? config.build.productionSourceMap // /config/index.js中设置的打包时是否生成map文件
: config.dev.cssSourceMap // /config/index.js中设置开发环境下是否生成css文件map
module.exports = {
// 默认生产环境和开发环境都需要生成map文件。默认只有生产环境才需要将css提取到单独的文件
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled, // 是否生成map文件
extract: isProduction // 生产环境下提取css到一个css文件中
}),
cssSourceMap: sourceMapEnabled, // 是否生成map文件
cacheBusting: config.dev.cacheBusting, // 是否破坏缓存,知否不需要缓存,开发环境下不需要缓存
// 在模版编译过程中,编译器可以将某些属性,如 src 路径,转换为require调用,以便目标资源可以由 webpack 处理
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
------webpack.base.conf.js文件:该文件是生产和开发环境共同使用提取出的基本设置,主要设置webpack打包的入口文件,输出路径,配置模块resovle和插件等
'use strict' // js 使用严格模式
const path = require('path') // 文件路径处理
const utils = require('./utils') // css处理utils方法
const config = require('../config') // 项目设置文件config/index.js
const vueLoaderConfig = require('./vue-loader.conf') // .vue文件处理配置
// 将工作区文件路径转换为绝对路径
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
// 对于以.js和.vue后缀结尾的文件(在src目录下或test目录下的文件),使用eslint进行文件语法检测。
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
module.exports = {
context: path.resolve(__dirname, '../'),
// 编译入口文件
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 // 开发环境下编译输出的发布路径
},
// 配置模块如何被解析。 https://webpack.docschina.org/configuration/resolve/
resolve: {
extensions: ['.js', '.vue', '.json'], // 自动补全的扩展名,能够使用户在引入模块时不带扩展名
// 路径代理
alias: {
'vue$': 'vue/dist/vue.esm.js', // import Vue from 'vue$',会自动到 'vue/dist/vue.esm.js'中寻找
'@': resolve('src'), // import test1 from '@/test1',自动导入 import test1 form 'src/test1'
}
},
// loader 列表,预处理文件。https://webpack.docschina.org/loaders/
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []), // 在开发环境下 对于以.js或.vue后缀结尾的文件(在src目录下或test目录下的文件),使用eslint进行文件语法检测。
{
test: /\.vue$/, // .vue后缀的文件,使用vue-loader处理,其他配置使用vue-loader.conf.js的配置
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,// .js后缀的文件,使用babel-loader转换,包括范围在include中设置
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, // 图片文件,使用url-loader转换
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]') // 打包后的文件名和打包后的位置
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, // 音频视频文件,使用url-loader转换
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')// 打包后的文件名和打包后的位置
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, // 字体文件,使用url-loader转换
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')// 打包后的文件名和打包后的位置
}
}
]
},
// Node.js全局变量或模块,这里主要是防止webpack注入一些Node.js的东西到vue中
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'
}
}
------webpack.dev.conf.js文件:开发环境webpack打包配置
'use strict' // 使用js严格模式
const utils = require('./utils') // 导入css uitls处理方法,uitis.js
const webpack = require('webpack') // 导入webpack
const config = require('../config') // 导入项目配置文件,/config/index.js
const merge = require('webpack-merge') // 导入webpack配置合并插件
const path = require('path') // 导入路径处理
const baseWebpackConfig = require('./webpack.base.conf') // 导入webpack打包通用基础配置
const CopyWebpackPlugin = require('copy-webpack-plugin') // webpack打包时的复制插件,将文件复制到打包后的目录
const HtmlWebpackPlugin = require('html-webpack-plugin') // 用于自动生成 html 并且注入到 .html 文件中
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') // 可以识别某些类别的Webpack错误并进行清理,聚合和优先排序。https://www.npmjs.com/package/friendly-errors-webpack-plugin
const portfinder = require('portfinder') // 用于获取 port。 https://npm.taobao.org/package/portfinder
const HOST = process.env.HOST // 当前环境的域名
const PORT = process.env.PORT && Number(process.env.PORT) // 当前环境的port端口
// 开发环境webpack配置,合并通用基本配置
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
// 使用styleLoaders,并进行配置
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
// 使用 cheap-module-eval-source-map 模式作为开发辅助调试工具
// 具体配置请参考https://doc.webpack-china.org/configuration/devtool/
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: { // https://webpack.js.org/configuration/dev-server/
clientLogLevel: 'warning', // 日志等级
historyApiFallback: { // 刷新和退回页面,找不到页面时的配置
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }, // 找不到页面就返回首页
],
},
hot: true, // 局部刷新,开发时修改内容后,不需要全部刷新页面时局部刷新
contentBase: false, // since we use CopyWebpackPlugin. // 不使用
compress: true, // 压缩文件
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser, // 是否自动打开页面
overlay: config.dev.errorOverlay // 是否覆盖错误信息
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath, // 资源路径
proxy: config.dev.proxyTable, // proxy代理配置
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: { // 观看设置 https://webpack.js.org/configuration/watch/
poll: config.dev.poll, // 不启用
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env') // definePlugin 接收字符串插入到代码当中, 需要的话可以写上 JS 的字符串
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
// HotModule 插件在页面进行变更的时候只会重回对应的页面模块,不会重绘整个 html 文件
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
//https://doc.webpack-china.org/plugins/no-emit-on-errors-plugin/
//在编译出现错误时,使用 NoEmitOnErrorsPlugin 来跳过输出阶段。这样可以确保输出资源不会包含错误。
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
// 将 index.html 作为入口,注入 html 代码后生成 index.html文件
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: ['.*'] // 忽略
}
])
]
})
// 检查port,没有问题就输出开发环境配置信息
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文件:生产环境webpack打包配置文件
'use strict' // js使用严格模式
const path = require('path') // 文件路径处理
const utils = require('./utils') // utils方法,主要出里css loader
const webpack = require('webpack')// 导入webpack
const config = require('../config') // 项目配置文件 config/index.js
const merge = require('webpack-merge') // webpack配置合并插件
const baseWebpackConfig = require('./webpack.base.conf') // webpack通用基础设置
const CopyWebpackPlugin = require('copy-webpack-plugin') // webpack打包时文件复制插件
const HtmlWebpackPlugin = require('html-webpack-plugin') // 读取生成html插件
// 一个 webpack 扩展,可以提取一些代码并且将它们和文件分离开
// 如果我们想将 webpack 打包成一个文件 css js 分离开,那我们需要这个插件
const ExtractTextPlugin = require('extract-text-webpack-plugin')
//一个个优化/最小化css资源的插件
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 压缩js插件
// 当前环境,是测试环境还是生产环境
const env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: require('../config/prod.env')
// webpack设置
const webpackConfig = merge(baseWebpackConfig, {
// 使用styleLoaders,并进行配置
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
// #source-map
devtool: config.build.productionSourceMap ? config.build.devtool : 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
// definePlugin 接收字符串插入到代码当中, 所以你需要的话可以写上 JS 的字符串
new webpack.DefinePlugin({
'process.env': env
}),
// 压缩js 配置
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
// 将css 提取出来
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.
// 压缩css
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
// 输出的html
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
// 模块没有改变时,使用模块的id
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
//将引用的库文件拆出来打包到一个[name].js文件中
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
//把webpack的runtime和manifest这些webpack管理所有模块交互的代码打包到[name].js文件中,防止build之后vendor的hash值被更新
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
//复制自定义的静态资源文件到dist/static文件夹中
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
// 开启 gzip 的情况下使用下方的配置,默认未开启
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
config文件夹:项目设置文件夹,内部文件用于设置项目的环境
------index.js文件:生产和开发环境共同使用基础配置文件
'use strict' // js 使用严格模式
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path') // 文件路径处理
module.exports = {
// 开发环境
dev: {
// Paths
assetsSubDirectory: 'static', // 编译输出的二级目录
assetsPublicPath: '/', // 打包后,index.html里面引用资源的的相对地址,/为绝对路径。 ./为相对路径。也可配置为资源服务器域名或 CDN 域名
proxyTable: {}, // 需要 proxyTable 代理的接口(可跨域)http://vuejs-templates.github.io/webpack/proxy.html
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST // 域名
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined // 端口
autoOpenBrowser: true, // 启动项目后是否自动打开页面
errorOverlay: true, // 是否覆盖错误信息
notifyOnErrors: true, // 是否进行错误提示
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true, // 是否使用eslint检查代码
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false, // 是否覆盖eslint错误信息
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map', // 开发辅助调试工具
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true, // 是否清除缓存
cssSourceMap: true // 是否生成css map文件
},
// 生产环境
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'), // 打包后生成index.html文件和其路径
// Paths
assetsRoot: path.resolve(__dirname, '../dist'), // 打包后的根目录
assetsSubDirectory: 'static', // 打包后的二级目录
assetsPublicPath: '/', // 打包后的文件引入路径,绝对路径。./为相对路径。也可设置为域名
/**
* Source Maps
*/
productionSourceMap: true, // 生成map文件
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map', // 生产环境下开发辅助调试工具
// 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文件,需要哪些文件类型生成
// 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.env.js文件:开发环境项目配置
'use strict' // js使用严格模式
const merge = require('webpack-merge') // webpack配置合并
const prodEnv = require('./prod.env') // 生产环境下项目配置
// 将开发环境下项目配置合并到生产环境配置上
module.exports = merge(prodEnv, {
NODE_ENV: '"development"' // 环境为开发环境
})
------prod.env.js文件:生产环境项目配置
'use strict'
module.exports = {
NODE_ENV: '"production"' // 环境为生产环境
}
------test.env.js文件:测试环境配置
'use strict' // js使用严格模式
const merge = require('webpack-merge') // webpack配置合并插件
const devEnv = require('./dev.env') // 项目开发环境配置
// 合并测试环境配置到开发环境配置上
module.exports = merge(devEnv, {
NODE_ENV: '"testing"' // 设置环境为开发环境
})
node_modules文件夹:项目依赖项文件夹,内部为项目以来的插件
src文件夹:项目开发文件夹,内部为具体的项目开发文件
------asstes文件夹为静态资源文件夹,与static文件夹的却别是asstes文件夹下的静态资源webpack打包时会进行打包。static下的会直接复制
------components文件夹:vue组件文件夹,可以将项目中使用的组件放到该文件夹下
------router文件夹:项目路由文件夹,使用vue-router插件时,需要设置跳转路由,放在此文件夹下
------app.vue文件:项目挂载vue根实例的vue根组件
------main.js文件:项目入口文件,在此文件中引入项目需要的插件,注册插件等
static文件夹:项目静态资源文件夹,项目所用到的静态资源,图片,css,plugins等等静态资源,如果不希望打包项目时打包到js中都可以放到此文件夹中。该文件夹下的文件在打包时,会被整体复制到打包路径下
test文件夹:项目测试文件夹,用于项目的功能测试
3:文件介绍
.babelrc文件:项目js文件转码规则设置,使用bable转换js格式时使用此文件中的设置(不需要重新配置)
.editconfig文件:编辑器代码风格设置,设置编辑代码时的代码风格,方便不同的编辑器能够保持代码风格一致(不需要重新配置)
.eslintignore文件:设置eslint忽略检查的文件夹和文件(不需要重新配置)
.eslintrc文件:配置eslint检查规则(不需要重新配置)
.gitignore文件:设置git忽略掉的文件夹和文件,被忽略的文件夹和文件不在版本控制中,不会被git提交和检查(可根据项目具体情况增加相应的配置)
.postcssrc文件:配置css样式添加不同的浏览器私有前缀,用于兼容不用的浏览器。(不需要重新配置)
index.html文件:项目初始页面,vue项目中各个组件都是渲染进该页面中
package.json文件:配置项目基本信息,项目依赖项,项目运行命令等
README.md文件:使用markdown语法编写的项目基本信息文件

303

被折叠的 条评论
为什么被折叠?



