主体结构
├─build webpack的一些配置文件以及服务启动文件
├─config 多为build中所依赖的文件
├─dist
├─node_modules
├─src 页面以及逻辑文件夹
│ ├─assets
│ ├─components
│ ├─router
│ ├─App.vue
│ ├─main.js
├─static 字体以及公众样式文件夹
├─.babelrc es6编译文件配置
├─.editorconfig 编写风格配置文件,比如缩进文件格式
├─.eslintignore 忽略检测一些文件格式
├─.eslintrc.js 代码规范化配置文件
├─.gitignore 忽略上传一些文件或配置
├─.postcssrc.js 用js来处理css
├─index.html 主文件入口
├─package-lock.json
├─package.json npm依赖以及开发生产环境用的模块包
└─README.md 解释说明项目是做什么的
package.json
npm install
命令根据这个配置文件增减来管理本地的安装包。
//从name到private都是package的配置信息,也就是我们在脚手架搭建中输入的项目描述
{
//项目名称:不能以.(点)或者_(下划线)开头,不能包含大写字母,具有明确的的含义与现有项目名字不重复
"name": "learn",
"version": "1.0.0", //项目版本号:遵循“大版本.次要版本.小版本”
"description": "A Vue.js project", //项目描述
"author": "WSQ", //作者名字
"private": true, //是否私有
"scripts": { //scripts中的子项即是我们在控制台运行的脚本的缩写
//webpack-dev-server:启动了http服务器,实现实时编译;
//inline模式会在webpack.config.js入口配置中新增webpack-dev-server/client?http://localhost:8080/的入口,
//使得我们访问路径为localhost:8080/index.html(相应的还有另外一种模式Iframe);
//progress:显示打包的进度
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev", //与npm run dev相同,直接运行开发环境
"lint": "eslint --ext .js,.vue src",
"build": "node build/build.js" //使用node运行build文件
},
//dependencies(项目依赖库):在安装时使用--save则写入到dependencies
"dependencies": {
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
//devDependencies(开发依赖库):在安装时使用--save-dev将写入到devDependencies
"devDependencies": {
//autoprefixer作为postcss插件用来解析CSS补充前缀,
//例如display:flex会补充为display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex
"autoprefixer": "^7.1.2",
//babel:以下几个babel开头的都是针对es6解析的插件。用最新标准编写的JavaScript代码向下编译成可以在今天随处可用的版本
"babel-core": "^6.22.1", //babel的核心,把js代码分析成ast ,方便各个插件分析语法进行相应的处理
"babel-eslint": "^8.2.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3", //预制babel-template函数,提供给vue,jsx等使用
"babel-loader": "^7.1.1", //使项目运行使用Babel和webpack来传输js文件,使用babel-core提供的api进行转译
"babel-plugin-syntax-jsx": "^6.18.0", //支持jsx
"babel-plugin-transform-runtime": "^6.22.0", //避免编译输出中的重复,直接编译到build环境中
"babel-plugin-transform-vue-jsx": "^3.5.0", //babel转译过程中使用到的插件,避免重复
"babel-preset-env": "^1.3.2", //转为es5,transform阶段使用到的插件之一
"babel-preset-stage-2": "^6.22.0", //ECMAScript第二阶段的规范
"chalk": "^2.0.1", //用来在命令行输出不同颜色文字
"copy-webpack-plugin": "^4.0.1", //拷贝资源和文件
//webpack先用css-loader加载器去解析后缀为css的文件,再使用style-loader生成一个内容为最终解析完的css代码的style标签,放到head标签里
"css-loader": "^0.28.0",
"eslint": "^4.15.0",
"eslint-config-standard": "^10.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^3.0.1",
"eslint-plugin-vue": "^4.0.0",
"extract-text-webpack-plugin": "^3.0.0", //将一个以上的包里面的文本提取到单独文件中
"file-loader": "^1.1.4", //打包压缩文件,与url-loader用法类似
"friendly-errors-webpack-plugin": "^1.6.1", //识别某些类别的webpack错误和清理,聚合和优先排序,以提供更好的开发经验
"html-webpack-plugin": "^2.30.1", //简化了HTML文件的创建,引入了外部资源,创建html的入口文件,可通过此项进行多页面的配置
"node-notifier": "^5.1.2", //支持使用node发送跨平台的本地通知
//压缩提取出的css,并解决ExtractTextPlugin分离出的js重复问题(多个文件引入同一css文件)
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0", //加载(loading)的插件
"portfinder": "^1.0.13", //查看进程端口
"postcss-import": "^11.0.0", //可以消耗本地文件、节点模块或web_modules
"postcss-loader": "^2.0.8", //用来兼容css的插件
"postcss-url": "^7.2.1", //URL上重新定位、内联或复制
"rimraf": "^2.6.0", //节点的UNIX命令RM—RF,强制删除文件或者目录的命令
"semver": "^5.3.0", //用来对特定的版本号做判断的
"shelljs": "^0.7.6", //使用它来消除shell脚本在UNIX上的依赖性,同时仍然保留其熟悉和强大的命令,即可执行Unix系统命令
"uglifyjs-webpack-plugin": "^1.1.1", //压缩js文件
"url-loader": "^0.5.8", //压缩文件,可将图片转化为base64
"vue-loader": "^13.3.0", //VUE单文件组件的webpack加载器
"vue-style-loader": "^3.0.1", //类似于样式加载程序,您可以在CSS加载器之后将其链接,以将CSS动态地注入到文档中作为样式标签
"vue-template-compiler": "^2.5.2", //这个包可以用来预编译VUE模板到渲染函数,以避免运行时编译开销和CSP限制
"webpack": "^3.6.0", //打包工具
"webpack-bundle-analyzer": "^2.9.0", //可视化webpack输出文件的大小
"webpack-dev-server": "^2.9.1", //提供一个提供实时重载的开发服务器
//它将数组和合并对象创建一个新对象。如果遇到函数,它将执行它们,通过算法运行结果,然后再次将返回的值封装在函数中
"webpack-merge": "^4.1.0"
},
//engines是引擎,指定node和npm版本
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
//限制了浏览器或者客户端需要什么版本才可运行
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
devDependencies
和dependencies
的区别:devDependencies
里面的插件只用于开发环境,不用于生产环境,即辅助作用,打包的时候需要,打包完成就不需要了。而dependencies
是需要发布到生产环境的,自始至终都在。比如wepack等只是在开发中使用的包就写入到devDependencies
,而像vue
这种项目全程依赖的包要写入到devDependencies
。
file-loader
和url-loader
的区别:以图片为例,file-loader
可对图片进行压缩,但是还是通过文件路径进行引入,当http
请求增多时会降低页面性能,而url-loader
通过设定limit参数,小于limit
字节的图片会被转成base64
的文件,大于limit
字节的将进行图片压缩的操作。总而言之,url-loader
是file-loader
的上层封装。
.postcssrc.js
.postcssrc.js
文件其实是postcss-loader
包的一个配置,里面写进去需要使用到的插件。
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
"autoprefixer": {}
}
}
.babelrc
该文件是es6解析的一个配置。
{
//制定转码的规则
"presets": [
//env是使用babel-preset-env插件将js进行转码成es5,
//并且设置不转码的AMD,COMMONJS的模块文件,制定浏览器的兼容
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"]
}
src内文件
我们开发的代码都存放在src
目录下,根据需要我们通常会再建一些文件夹。比如pages
的文件夹,用来存放页面让components
文件夹专门做好组件的工作;api
文件夹,来封装请求的参数和方法;store
文件夹,使用vuex
来作为vue
的状态管理工具,我也常叫它作前端的数据库等。
-
assets
文件:脚手架自动回放入一个图片在里面作为初始页面的logo
。平常我们使用的时候会在里面建立js
,css
,img
,fonts
等文件夹,作为静态资源调用。 -
components
文件夹:用来存放组件,合理地使用组件可以高效地实现复用等功能,从而更好地开发项目。一般情况下比如创建头部组件的时候,我们会新建一个header
的文件夹,然后再新建一个header.vue
的文件夹。 -
router
文件夹:该文件夹下有一个叫index.js
文件,用于实现页面的路由跳转。 -
App.vue
:作为我们的主组件,可通过使用开放入口让其他的页面组件得以显示。 -
main.js
:作为我们的入口文件,主要作用是初始化vue
实例并使用需要的插件,小型项目省略router
时可放在该处。
其他文件
-
.editorconfig
:编辑器的配置文件 -
.gitignore
:忽略git提交的一个文件,配置之后提交时将不会加载忽略的文件 -
index.html
:页面入口,经过编译之后的代码将插入到这来。 -
package.lock.json
:锁定安装时的包的版本号,并且需要上传到git
,以保证其他人在npm install
时大家的依赖能保证一致 - README.md:可此填写项目介绍
- node_modules:根据
package.json
安装时候生成的的依赖(安装包)
config文件夹
├─config
│ ├─dev.env.js
│ ├─index.js
│ ├─prod.env.js
config/dev.env.js
config
内的文件其实是服务于build
的,大部分是定义一个变量export
出去。
'use strict' //采用严格模式
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
//webpack-merge提供了一个合并函数,它将数组和合并对象创建一个新对象。
//如果遇到函数,它将执行它们,通过算法运行结果,然后再次将返回的值封装在函数中.这边将dev和prod进行合并
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
config/prod.env.js
当开发是调取dev.env.js
的开发环境配置,发布时调用prod.env.js
的生产环境配置。
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
config/index.js
'use strict'
// Template version: 1.3.1
const path = require('path')
module.exports = {
dev: { // 开发环境下面的配置
// 路径相关配置
assetsSubDirectory: 'static', //子目录,一般存放css,js,image等文件
assetsPublicPath: '/', //根目录
proxyTable: {}, //可利用该属性解决跨域的问题
// 各种开发服务器设置
host: 'localhost', // 地址
port: 8080, // 端口号设置,端口号占用出现问题可在此处修改
//是否在编译(输入命令行npm run dev)后打开http://localhost:8080/页面,以前配置为true,近些版本改为false
autoOpenBrowser: false,
errorOverlay: true, //浏览器错误提示
notifyOnErrors: true, //跨平台错误提示
poll: false, //使用文件系统(file system)获取文件改动的通知devServer.watchOptions
// 如果用了ESlint,代码会捆绑和连接错误和警告显示在控制台中
useEslint: true,
//eslint错误和警告也将显示在浏览器的错误中。
showEslintErrorsInOverlay: false,
devtool: 'cheap-module-eval-source-map', //增加调试,该属性为原始源代码(仅限行)不可在生产环境中使用
// 如果在devtools中调试vue文件有问题,请将其设置为false——这可能会有帮助。
cacheBusting: true, //使缓存失效
//代码压缩后进行调bug定位将非常困难,于是引入sourcemap记录压缩前后的位置信息记录,
//当产生错误时直接定位到未压缩前的位置,将大大的方便我们调试
cssSourceMap: true
},
// 生产环境下面的配置
build: {
//index编译后生成的位置和名字,根据需要改变后缀,比如index.php
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'), //编译后存放生成环境代码的位置
assetsSubDirectory: 'static', //js,css,images存放文件夹名
//发布的根目录,通常本地打包dist后打开文件会报错,此处修改为./。
//如果是上线的文件,可根据文件存放位置进行更改路径
assetsPublicPath: '/',
productionSourceMap: true,
devtool: '#source-map',
//unit的gzip命令用来压缩文件,gzip模式下需要压缩的文件的扩展名有js和css
// 默认情况下,像Surge或Netlify这样的流行静态主机已经为您压缩了所有静态资源。
//在设置为“true”之前,请确保安装了:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// 在构建完成后,用额外的参数运行构建命令来查看包分析器报告:
// npm run build --report
// 设置为“true”或“false”,以打开或关闭它
bundleAnalyzerReport: process.env.npm_config_report
}
}
build文件夹
├─build
│ ├─build.js
│ ├─check-versions.js
│ ├─utils.js
│ ├─vue-loader.conf.js
│ ├─webpack.base.conf.js
│ ├─webpack.dev.conf.js
│ ├─webpack.prod.conf.js
build/build.js
该文件作用,即构建生产版本。package.json
中的scripts
的build
就是node build/build.js
,输入命令行npm run build
对该文件进行编译生成生产环境的代码。
'use strict'
require('./check-versions')() //调用检查版本的文件,加()代表直接调用该函数
process.env.NODE_ENV = 'production' //设置当前环境为production
//下面定义常量引入插件
const ora = require('ora') //加载动画
const rm = require('rimraf') //Node环境下rm -rf的命令库
const path = require('path') //文件路径处理
const chalk = require('chalk') //对文案输出的一个彩色设置
const webpack = require('webpack')
const config = require('../config') //默认读取下面的index.js文件
const webpackConfig = require('./webpack.prod.conf') //生产环境下的webpack配置
const spinner = ora('building for production...')
spinner.start() //调用start的方法实现加载动画,优化用户体验
//先删除dist文件再生成新文件,因为有时候会使用hash来命名,删除整个文件可避免冗余
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop() //停止loading
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
//如果使用的是ts-loader,将其设置为true将会在构建期间出现TypeScript错误
children: false,
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'
))
})
})
build/check-version.js
该文件用于检测node
和npm
的版本,实现版本依赖。
'use strict'
const chalk = require('chalk')
const semver = require('semver') //对版本进行检查
const packageConfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
//返回通过child_process模块的新建子进程,执行Unix系统命令后转成没有空格的字符串
return require('child_process').execSync(cmd).toString().trim()
}
const versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version), //使用semver格式化版本
versionRequirement: packageConfig.engines.node //获取package.json中设置的node版本
}
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
// 自动调用npm --version命令,并且把参数返回给exec函数,从而获取纯净的版本号
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
//上面这个判断就是如果版本号不符合package.json文件中指定的版本号,就执行下面错误提示的代码
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)
}
}
build/utils.js
utils.js
是一个用来处理css
的文件。
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
//导出文件的位置,根据环境判断开发环境和生产环境,
//为config文件中index.js文件中定义的build.assetsSubDirectory或dev.assetsSubDirectory
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
//Node.js path 模块提供了一些用于处理文件路径的小工具
return path.posix.join(assetsSubDirectory, _path)
}
//使用了css-loader和postcssLoader,通过options.usePostCSS属性来判断是否使用postcssLoader中压缩等方法
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: { //css-loader的选项配置
sourceMap: options.sourceMap //根据参数是否要生成sourceMap文件
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// 生成加载器字符串用于提取文本插件
function generateLoaders (loader, loaderOptions) { //生成loader
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
//Object.assign是es6语法的浅复制,将loaderOptions和sourceMap合并成一个对象后复制完成赋值
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// 在指定该选项时提取CSS
if (options.extract) { //如果options存在extract并且为true
//ExtractTextPlugin可提取出文本,代表首先使用上面处理的loaders,当未能正确引入时使用vue-style-loader
return ExtractTextPlugin.extract({ //ExtractTextPlugin分离js中引入的css文件
use: loaders, //处理loader
fallback: 'vue-style-loader' //没有被提取分离时使用的loader
})
} else {
//返回vue-style-loader连接loaders的最终值
return ['vue-style-loader'].concat(loaders)
}
}
return { //返回css类型对应的loader组成的对象 generateLoaders()来生成loader
css: generateLoaders(), //需要css-loader和vue-style-loader
postcss: generateLoaders(), //需要css-loader和postcssLoader 和vue-style-loader
less: generateLoaders('less'), //需要less-loader和vue-style-loader
sass: generateLoaders('sass', { indentedSyntax: true }), //需要sass-loader和vue-style-loader
scss: generateLoaders('sass'), //需要sass-loader和vue-style-loader
stylus: generateLoaders('stylus'), //需要stylus-loader和vue-style-loader
styl: generateLoaders('stylus') //需要stylus-loader和vue-style-loader
}
}
// 为独立样式文件生成加载器(在.vue之外)
exports.styleLoaders = function (options) {
const output = []
//调用cssLoaders方法返回各类型的样式对象
const loaders = exports.cssLoaders(options)
for (const extension in loaders) { //遍历loaders
//根据遍历获得的key(extension)来得到value(loader)
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')
})
}
}
path.posix
:提供对路径方法的POSIX(可移植性操作系统接口)特定实现的访问,即可跨平台,区别于win32。
path.join
:用于连接路径,会正确使用当前系统的路径分隔符,Unix系统是"/",Windows系统是""
vue-loader.conf.js
该文件的主要作用就是处理.vue
文件,解析这个文件中的每个语言块(template
、script
、style
),转换成js
可用的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
//处理项目中的css文件,生产环境和测试环境默认是打开sourceMap,
//而extract中的提取样式到单独文件只有在生产环境中才需要
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
// 在模版编译过程中,编译器可以将某些属性,如 src 路径,转换为require调用,以便目标资源可以由 webpack 处理.
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
webpack.base.conf.js
webpack.base.conf.js
是开发和生产共同使用提出来的基础配置文件,主要实现配制入口,配置输出环境,配置模块resolve
和插件等。
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
//拼接出绝对路径
return path.join(__dirname, '..', dir)
}
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
}
})
//path.join将路径片段进行拼接,而path.resolve将以/开始的路径片段作为根目录,在此之前的路径将会被丢弃
//path.join('/a', '/b') // 'a/b',path.resolve('/a', '/b') // '/b'
module.exports = {
context: path.resolve(__dirname, '../'),
//配置入口,默认为单页面所以只有app一个入口
entry: {
app: './src/main.js'
},
//配置出口,默认是/dist作为目标文件夹的路径
output: {
path: config.build.assetsRoot, //导出目录的绝对路径
filename: '[name].js', //导出文件的文件名
//生产模式或开发模式下的html、js等文件内部引用的公共路径
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: { //文件解析
//自动解析确定的扩展名,使导入模块时不带扩展名
extensions: ['.js', '.vue', '.json'],
//创建import或require的别名
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: { //模块解析,如何处理项目中不同类型的模块
//使用vue-loader将vue文件转化成js的模块
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig //对vue-loader做额外的选项配置
},
//js文件需要通过babel-loader进行编译成es5文件以及压缩等操作
{
test: /\.js$/,
loader: 'babel-loader',
//必须处理包含src、test和client的文件夹
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
//图片、音像、字体都使用url-loader进行处理,超过10000会编译成base64
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
//文件名为name.7位hash值.扩展名
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.js全局变量或模块,这里主要是防止webpack注入一些Node.js的东西到vue中
node: {
setImmediate: false,
// 防止webpack向节点本地模块注入模拟,这对客户端来说是没有意义的
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
webpack.dev.conf.js
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
//通过webpack-merge实现webpack.dev.conf.js对wepack.base.config.js的继承
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')
//美化webpack的错误信息和日志的插件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// 查看空闲端口位置,默认情况下搜索8000这个端口
const portfinder = require('portfinder')
/processs为node的一个全局对象获取当前程序的环境变量,即host
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
//规则是工具utils中处理出来的styleLoaders,生成了css,less,postcss等规则
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool, //增强调试,上文有提及
//此处的配置都是在config的index.js中设定好了
devServer: {
clientLogLevel: 'warning', //控制台显示的选项有none, error, warning 或者 info
//当使用H5 History API时,任意的404响应都可能需要被替代为index.html
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, // warning 和 error 都要显示
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable, //接口代理
quiet: true, //控制台是否禁止打印警告和错误,若用FriendlyErrorsPlugin 此处为 true
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({ //编译时配置的全局变量
'process.env': require('../config/dev.env') //当前环境为开发环境
}),
//模块热替换插件,修改模块时不需要刷新页面
new webpack.HotModuleReplacementPlugin(), //热更新插件
new webpack.NamedModulesPlugin(), // 显示文件的正确名字
//不触发错误,即编译后运行的包正常运行
new webpack.NoEmitOnErrorsPlugin(),
//自动生成html文件,比如编译后文件的引用
new HtmlWebpackPlugin({
filename: 'index.html', //生成的文件名
template: 'index.html', //模板
inject: true
}),
//复制插件
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 {
// 发布e2e测试所需的新端口
//端口被占用时就重新设置evn和devServer的端口
process.env.PORT = port
// 添加端口到devServer配置
devWebpackConfig.devServer.port = port
// 添加 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
'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 = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
//调用utils.styleLoaders的方法
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap, //开启调试的模式。默认为true
extract: true,
usePostCSS: true
})
},
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: [
new webpack.DefinePlugin({
'process.env': env //配置全局环境为生产环境
}),
new UglifyJsPlugin({ //js压缩插件
uglifyOptions: {
compress: { //压缩配置
warnings: false //警告:true保留警告,false不保留
}
},
sourceMap: config.build.productionSourceMap, //生成sourceMap文件
parallel: true
}),
//抽取文本。比如打包之后的index页面有css插入,就是这个插件抽取出来的,减少请求
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'), //分离出来的css文件名
allChunks: true,
}),
//压缩提取出的css,并解决ExtractTextPlugin分离出的js重复问题(多个文件引用同一个css文件)
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
new HtmlWebpackPlugin({ //生成html的插件,引入css文件和js文件
filename: config.build.index, //生成的html的文件名
template: 'index.html', //依据的模板
inject: true, //注入的js文件会被放在body标签中,当值为head的时候将被放在head标签中
minify: { //压缩配置
removeComments: true, //删除html中的注释代码
collapseWhitespace: true, //删除html中的空格
removeAttributeQuotes: true //删除html元素中属性的引号
},
chunksSortMode: 'dependency' //模块排序,按照我们需要的顺序排序
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({ //分离公共js到vendor中
name: 'vendor',
minChunks (module) { //声明公告的模块来自Node_modules文件夹
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
//复制静态资源,将static文件内的内容复制到指定文件夹
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*'] //忽略.*文件
}
])
]
})
if (config.build.productionGzip) { //配置文件开启gzip压缩
//引入压缩文件的组件,该插件会对生成的文件进行压缩,生成一个.gz文件
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]', //目标文件名
algorithm: 'gzip', //使用gzip压缩
test: new RegExp( //满足正值表达式的文件会被压缩
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240, //资源文件大于10kb的时候会被压缩
minRatio: 0.8 //最小压缩比达到0.8的时候会被压缩
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig