召唤师名称:
12 |{{name}}
13 |背景介绍:
14 |{{explain}}
15 |├── .vscode └── launch.json ├── README.md └── express-mongodb-vue ├── .babelrc ├── .editorconfig ├── .gitignore ├── .postcssrc.js ├── README.md ├── app.js ├── build ├── build.js ├── check-versions.js ├── logo.png ├── utils.js ├── vue-loader.conf.js ├── webpack.base.conf.js ├── webpack.dev.conf.js └── webpack.prod.conf.js ├── config ├── db.js ├── dev.env.js ├── index.js └── prod.env.js ├── index.html ├── models └── heroSchema.js ├── package-lock.json ├── package.json ├── router └── hero.js ├── src ├── App.vue ├── assets │ ├── css │ │ └── index.css │ ├── icon │ │ ├── iconfont.css │ │ ├── iconfont.eot │ │ ├── iconfont.svg │ │ ├── iconfont.ttf │ │ └── iconfont.woff │ └── image │ │ └── loginBg.jpg ├── components │ ├── Detail.vue │ ├── List.vue │ └── Login.vue ├── main.js ├── permission.js ├── router │ └── index.js └── utils │ ├── mongoSql.js │ ├── request.js │ ├── user.js │ └── validate.js └── static └── .gitkeep /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // 使用 IntelliSense 了解相关属性。 3 | // 悬停以查看现有属性的描述。 4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "启动程序", 11 | "program": "${workspaceFolder}/express-mongodb-vue/app.js" 12 | } 13 | ] 14 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## express+mongodb+vue实现增删改查-全栈之路2.0 2 | 3 | 前后端分离实现增删改查Demo 4 | 5 | ## 效果图 6 | 7 | ### 登陆页 8 |  9 | ### 查询 10 |  11 | ### 新增 12 |  13 | ### 修改 14 |  15 | ### 删除 16 |  17 | ### 详情页 18 |  19 | ## 技术栈 20 | `vue` `axios` `vue-router` `express` `mongo` `element` `iconfont` `scss` 21 | 22 | ## 前言 23 | 半年前写过一个[express+mongodb+vue][1]的项目,其中大致的给大家展示了从零构建一个前后台项目所需要的技术点和思路,以及在开发过程中遇到的一些坑。 24 | 25 | 之后收到一些小伙伴的私信包括[github][2]上提出的**issue**。总结一下就是一下以下两点。 26 | 27 | 1. 项目启动报错的问题 28 | 2. 希望案例可以更加的丰富(分页、条件查询) 29 | 30 | **其中项目报错404的问题,是因为该项目是一个前后端项目,不仅仅需要通过`npm run dev`启动前端,还需要通过终端`node app.js`启动后台。这里大家一定要注意!** 31 | 32 | > 本次版本是之前版本的升级版,项目中对部分代码做了一定的优化,也增加了一些新的模块和功能点,使得项目更加完善,大致有以下模块。 33 | 34 | 35 | ## 新增模块 36 | 37 | - 登陆页面 38 | - 条件查询 39 | - 分页查询 40 | - 本地缓存 41 | - 图标使用 42 | - scss使用 43 | - ...... 44 | 45 | ## 提示 46 | 本篇主要是围绕**本次版本新增**的一些技术点展开陈述。不会过多的给大家讲解实现整个前后端项目的思路。如果你对整个项目的搭建思路还不是很明确的话,建议您先去阅读上一个版本[express+mongodb+vue][3]。 47 | 48 | **强烈建议去我的[github][4]上,将项目下载到本地,启动项目后,顺着本文的思路与我进行灵魂深处的探讨,如果有任何问题的话,欢迎私信我!** 49 | 50 | # 正文 51 | 52 | ## 封装常用工具类函数 53 | 54 | 因为在真实的项目中,我们需要频繁的用到`ajax`获取数据,之前的版本,是采用`vue-resource`完成的,但是由于官方不再维护,所以本次版本中采用官方建议使用的[axios][5]。我们可以方便实现自定义`axios`实例,拦截器,请求添加字段等功能。 55 | 56 | 在`src`目录下面,有个`utils`文件夹,里面用来存放一些工具类函数,这些工具类函数应该是具有通用性的。也就是在不同的组件页面中都可以引用。实现一次定义,多次使用的目的。具体的工具类函数分类大致有以下一些点。 57 | 58 | - axios实例 59 | - 常用正则校验函数 60 | - cookie、sessionStorage添加、获取、删除方法 61 | - ...... 62 | 63 | **总之从事开发的同学们一定要有简化业务逻辑的思维,经常用到的模块,独立出来。** 64 | 65 | >Tips:文件命名和函数命名尽量标准一点,不要想起啥就是啥,尽量用对应的英文去命名,英文不好的去百度呗,磨刀不误砍柴工! 66 | 67 | ## 登陆页面的那点事 68 | 69 | 合理的登陆逻辑应该是以下两点: 70 | 71 | 1. 用户在查询英雄列表之前,首先需要登录,否则**重定向**到登录页面 72 | 2. 对于已经登录的用户,可以直接访问列表页 73 | 74 | 为了实现上述逻辑,我们可以使用[vue-router][6]中提供的前置守卫导航`beforeEach`配合`路由重定向`实现。具体代码参考`permission.js`文件。 75 | 76 | > Tips:这里要提醒以下大家路由导航中的`next`使用一定要注意,其中传参和不传参是有不同的效果的。我在开发的过程中,就因为这个,遇到了**无限循环**的坑。 77 | 78 | ## 更加丰富的图标选择 79 | 80 | 本项目使用的前端框架[element][7]中虽然为我们提供了一些常用的图标,但是在真实的开发场景中,是无法满足的。如果你还在用图片实现icon的话,我只想送你两个字——**牛逼**! 81 | 82 | [阿里巴巴iconfont][8]图标库,可以帮助我们解决框架提供图标不完善的问题,其中使用方法有三种,它们之间的利和弊可自行前往了解。本项目中使用的是`unicode`方式。 83 | 84 | 我们在开发一个项目之前,可在`阿里巴巴iconfont`上新建一个项目,然后去图标库中查找对应的图标,添加到项目中。再下载到本地,引入项目中即可。 85 | 86 | 项目`src`目录下面的`assets`文件夹中,主要存放一些静态资源,比如`css` `image` `icon`等。 87 | 88 | 然后在`main.js`文件中引入对应图标的css文件。 89 | 90 | #main.js 91 | 92 | import "./assets/icon/iconfont.css" 93 | 94 | 95 | 96 | > Tips:其中对于图标库的前缀命名和图标的命名一定要规范,否则后期可能会遇到很大的麻烦。 97 | 重要的事说三遍: 98 | 命名规范! 99 | 命名规范! 100 | 命名规范! 101 | 102 | ## scss的使用 103 | 104 | 之前的版本中,关于样式是用`css`进行命名的,这样就会出现以下这种情形... 105 | 106 | .container{ 107 | width:... 108 | margin:... 109 | } 110 | 111 | .container header{ 112 | padding:... 113 | border-radius:... 114 | box-shadow:... 115 | } 116 | .container header .title{ 117 | background:... 118 | color:... 119 | font-size:... 120 | } 121 | 122 | 这种方式虽然没有问题,但是书写起来及其蛋疼,而且一旦形如这种的代码多了,代码看起来也会很不美观。 123 | 124 | 为了使性能更加好,逼格更加高,代码更加美观,所以我去学了下如何使用`scss`,大致分为以下三步骤: 125 | 126 | 第一步:cmd终端或者**vscode**终端输入: 127 | npm install sass-loader --save-dev 128 | npm install node-sass --sava-dev 129 | 130 | 第二步:在build文件夹下的webpack.base.conf.js的rules里面添加配置 131 | { 132 | test: /\.scss$/, 133 | loaders: ['style', 'css', 'sass'] 134 | } 135 | 136 | 第三步: 使用scss时候在所在的style样式标签上添加lang=”scss”即可应用对应的语法,否则报错 137 | 138 | 再用scss语法去书写上面的css规则,则变成以下这种格式: 139 | 140 | .container{ 141 | width:... 142 | margin:... 143 | header:{ 144 | padding:... 145 | border-radius:... 146 | box-shadow:... 147 | .title{ 148 | background:... 149 | color:... 150 | font-size:... 151 | } 152 | } 153 | } 154 | 155 | **两种风格的区别和优劣,我相信不用多说,你也应该明白了。** 156 | 157 | > Tips:css的预处理器有less、sass、scss等,它们之间有各自的特点和风格,但是万变不离其宗,你要做的就是打好css基本功。 158 | 159 | ## sessionStorage实现本地缓存 160 | 161 | 就拿本案例的实际场景来说吧,当用户从列表页跳转到详情页面时,再返回列表页面时,列表页面的查询条件和查询结果应该还存在那里。而不是需要用户再次输入查询条件进行二次查询,这样做的好处主要有以下两点: 162 | 163 | >更加符合实际使用场景,减少用户使用成本 164 | 165 | 毕竟前端工程师是要用自己最大的技术能力让用户体验更佳卓越! 166 | 167 | 这里我的**思路**是: 168 | 169 | 1.用户输入查询条件后,进行列表查询 170 | 171 | 2.用户点击某条数据的相信按钮,跳转到详情页面(这时我们要去保存用户的查询条件和当前的页数) 172 | 173 | 3.用户从详情页返回列表页(在mounted钩子函数中,判断缓存中是否存在缓存数据,如果存在的话,则用缓存数据去进行查询) 174 | 175 | 注意用户每次进行查询后,我们需要将缓存给删除,否则用户可能刷新页面后缓存仍然存在,这里我们将添加缓存的时机选在(用户点击详情按钮的那一刻) 176 | 177 | **大致代码:** 178 | 179 | #List.vue组件中 180 | 181 | #点击详情按钮函数 182 | toDetail(id){ 183 | var queryParmas = { 184 | ... 185 | ... 186 | ... 187 | }; 188 | //在本地缓存中存储查询条件 189 | sessionStorage.queryParmas = JSON.stringify(queryParmas); 190 | 191 | } 192 | 193 | #查询函数 194 | search(){ 195 | ... 196 | ... 197 | ... 198 | //每次查询数据后,删除缓存 199 | sessionStorage.removeItem("queryParmas"); 200 | } 201 | 202 | #mounted钩子函数 203 | mounted(){ 204 | //进入页面判断是否存在缓存,如果有缓存,直接查询 205 | var sessionObj = sessionStorage.getItem("queryParmas"); 206 | if(sessionObj){ 207 | //取出缓存数据,包括上次查询条件和上次查询页数,进行查询 208 | } 209 | } 210 | 211 | > Tips:element中分页的使用中会存在一些坑,当使用上述缓存数据进行查询时,可能会出现页码的一些bug。这里我也没有细找原因,但是通过使用vue中的$nextTick方法控制分页的显隐,可以解决这个bug。具体的有兴趣可以了解下。 212 | 213 | 214 | ## 总结 215 | 216 | 本篇文章主要是围绕一些功能点和方案实现进行展开,同时也提出了一些个人建议。细心的你一定会发现,其实我提炼出的很多点,都可以围绕**前端性能优化**进行展开。其中里面还有很多好玩的,包括`http` `浏览器渲染机制` `重排、重绘` `函数节流、防抖`等需要我们去学习,这些会鞭策着我们,不断地去优化自己的程序。最终写出更加优质的代码! 217 | 218 | ## 最后的祝福 219 | 220 | **天青色等烟雨,而我在等你!动动你们的☝️️️,点个赞再走!** 221 | 222 | **2019即将到来,愿所有人牛逼!在这给你们🙏个早年!** 223 | 224 | **原创不易,且👣且珍惜!** 225 | 226 | [Github传送门][9] 227 | 228 | ☝️☝️☝️☝️☝️ 229 | 230 | **ruiwei88888@163.com** 231 | 232 | ☝️☝️☝️☝️☝️有任何问题,欢迎邮箱私信我! 233 | 234 | 235 | 236 | [1]: https://juejin.im/post/5aabc2caf265da239376d5ff 237 | [2]: https://github.com/weirui88888 238 | [3]: https://juejin.im/post/5aabc2caf265da239376d5ff 239 | [4]: https://github.com/weirui88888 240 | [5]: https://www.kancloud.cn/yunye/axios/234845 241 | [6]: https://router.vuejs.org/zh/guide/advanced/navigation-guards.html 242 | [7]: http://element-cn.eleme.io/#/zh-CN/ 243 | [8]: https://www.iconfont.cnment-cn.eleme.io/#/zh-CN/ 244 | [9]: https://github.com/weirui88888 245 | -------------------------------------------------------------------------------- /express-mongodb-vue/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { 4 | "modules": false, 5 | "targets": { 6 | "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] 7 | } 8 | }], 9 | "stage-2" 10 | ], 11 | "plugins": ["transform-vue-jsx", "transform-runtime"] 12 | } 13 | -------------------------------------------------------------------------------- /express-mongodb-vue/.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /express-mongodb-vue/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | /dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Editor directories and files 9 | .idea 10 | .vscode 11 | *.suo 12 | *.ntvs* 13 | *.njsproj 14 | *.sln 15 | -------------------------------------------------------------------------------- /express-mongodb-vue/.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | "postcss-import": {}, 6 | "postcss-url": {}, 7 | // to edit target browsers: use "browserslist" field in package.json 8 | "autoprefixer": {} 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /express-mongodb-vue/README.md: -------------------------------------------------------------------------------- 1 | ### 注意点 -------------------------------------------------------------------------------- /express-mongodb-vue/app.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const hero = require('./router/hero'); 3 | const mongoose = require("mongoose"); 4 | const bodyParser = require("body-parser"); 5 | const cookieParser = require('cookie-parser');// 6 | 7 | //这一句是连接上数据库 8 | var db = mongoose.connect('mongodb://localhost:27017/myDbs'); 9 | 10 | //这里的myDbs是数据库的名字,不是表的名字 11 | 12 | 13 | const app = express() 14 | app.use(bodyParser.json()); 15 | app.use(bodyParser.urlencoded({ extended: false })); 16 | app.use(cookieParser()); 17 | app.use('/api',hero) 18 | app.listen(3000,() => { 19 | console.log('app listening on port 3000.') 20 | }) 21 | 22 | 23 | -------------------------------------------------------------------------------- /express-mongodb-vue/build/build.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | require('./check-versions')() 3 | 4 | process.env.NODE_ENV = 'production' 5 | 6 | const ora = require('ora') 7 | const rm = require('rimraf') 8 | const path = require('path') 9 | const chalk = require('chalk') 10 | const webpack = require('webpack') 11 | const config = require('../config') 12 | const webpackConfig = require('./webpack.prod.conf') 13 | 14 | const spinner = ora('building for production...') 15 | spinner.start() 16 | 17 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 18 | if (err) throw err 19 | webpack(webpackConfig, (err, stats) => { 20 | spinner.stop() 21 | if (err) throw err 22 | process.stdout.write(stats.toString({ 23 | colors: true, 24 | modules: false, 25 | children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. 26 | chunks: false, 27 | chunkModules: false 28 | }) + '\n\n') 29 | 30 | if (stats.hasErrors()) { 31 | console.log(chalk.red(' Build failed with errors.\n')) 32 | process.exit(1) 33 | } 34 | 35 | console.log(chalk.cyan(' Build complete.\n')) 36 | console.log(chalk.yellow( 37 | ' Tip: built files are meant to be served over an HTTP server.\n' + 38 | ' Opening index.html over file:// won\'t work.\n' 39 | )) 40 | }) 41 | }) 42 | -------------------------------------------------------------------------------- /express-mongodb-vue/build/check-versions.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const chalk = require('chalk') 3 | const semver = require('semver') 4 | const packageConfig = require('../package.json') 5 | const shell = require('shelljs') 6 | 7 | function exec (cmd) { 8 | return require('child_process').execSync(cmd).toString().trim() 9 | } 10 | 11 | const versionRequirements = [ 12 | { 13 | name: 'node', 14 | currentVersion: semver.clean(process.version), 15 | versionRequirement: packageConfig.engines.node 16 | } 17 | ] 18 | 19 | if (shell.which('npm')) { 20 | versionRequirements.push({ 21 | name: 'npm', 22 | currentVersion: exec('npm --version'), 23 | versionRequirement: packageConfig.engines.npm 24 | }) 25 | } 26 | 27 | module.exports = function () { 28 | const warnings = [] 29 | 30 | for (let i = 0; i < versionRequirements.length; i++) { 31 | const mod = versionRequirements[i] 32 | 33 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 34 | warnings.push(mod.name + ': ' + 35 | chalk.red(mod.currentVersion) + ' should be ' + 36 | chalk.green(mod.versionRequirement) 37 | ) 38 | } 39 | } 40 | 41 | if (warnings.length) { 42 | console.log('') 43 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 44 | console.log() 45 | 46 | for (let i = 0; i < warnings.length; i++) { 47 | const warning = warnings[i] 48 | console.log(' ' + warning) 49 | } 50 | 51 | console.log() 52 | process.exit(1) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /express-mongodb-vue/build/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weirui88888/express-mongodb-node/ac31391720c81d611781dd73eec60b322dcaac15/express-mongodb-vue/build/logo.png -------------------------------------------------------------------------------- /express-mongodb-vue/build/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const config = require('../config') 4 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 5 | const packageConfig = require('../package.json') 6 | 7 | exports.assetsPath = function (_path) { 8 | const assetsSubDirectory = process.env.NODE_ENV === 'production' 9 | ? config.build.assetsSubDirectory 10 | : config.dev.assetsSubDirectory 11 | 12 | return path.posix.join(assetsSubDirectory, _path) 13 | } 14 | 15 | exports.cssLoaders = function (options) { 16 | options = options || {} 17 | 18 | const cssLoader = { 19 | loader: 'css-loader', 20 | options: { 21 | sourceMap: options.sourceMap 22 | } 23 | } 24 | 25 | const postcssLoader = { 26 | loader: 'postcss-loader', 27 | options: { 28 | sourceMap: options.sourceMap 29 | } 30 | } 31 | 32 | // generate loader string to be used with extract text plugin 33 | function generateLoaders (loader, loaderOptions) { 34 | const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] 35 | 36 | if (loader) { 37 | loaders.push({ 38 | loader: loader + '-loader', 39 | options: Object.assign({}, loaderOptions, { 40 | sourceMap: options.sourceMap 41 | }) 42 | }) 43 | } 44 | 45 | // Extract CSS when that option is specified 46 | // (which is the case during production build) 47 | if (options.extract) { 48 | return ExtractTextPlugin.extract({ 49 | use: loaders, 50 | fallback: 'vue-style-loader' 51 | }) 52 | } else { 53 | return ['vue-style-loader'].concat(loaders) 54 | } 55 | } 56 | 57 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 58 | return { 59 | css: generateLoaders(), 60 | postcss: generateLoaders(), 61 | less: generateLoaders('less'), 62 | sass: generateLoaders('sass', { indentedSyntax: true }), 63 | scss: generateLoaders('sass'), 64 | stylus: generateLoaders('stylus'), 65 | styl: generateLoaders('stylus') 66 | } 67 | } 68 | 69 | // Generate loaders for standalone style files (outside of .vue) 70 | exports.styleLoaders = function (options) { 71 | const output = [] 72 | const loaders = exports.cssLoaders(options) 73 | 74 | for (const extension in loaders) { 75 | const loader = loaders[extension] 76 | output.push({ 77 | test: new RegExp('\\.' + extension + '$'), 78 | use: loader 79 | }) 80 | } 81 | 82 | return output 83 | } 84 | 85 | exports.createNotifierCallback = () => { 86 | const notifier = require('node-notifier') 87 | 88 | return (severity, errors) => { 89 | if (severity !== 'error') return 90 | 91 | const error = errors[0] 92 | const filename = error.file && error.file.split('!').pop() 93 | 94 | notifier.notify({ 95 | title: packageConfig.name, 96 | message: severity + ': ' + error.name, 97 | subtitle: filename || '', 98 | icon: path.join(__dirname, 'logo.png') 99 | }) 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /express-mongodb-vue/build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const config = require('../config') 4 | const isProduction = process.env.NODE_ENV === 'production' 5 | const sourceMapEnabled = isProduction 6 | ? config.build.productionSourceMap 7 | : config.dev.cssSourceMap 8 | 9 | module.exports = { 10 | loaders: utils.cssLoaders({ 11 | sourceMap: sourceMapEnabled, 12 | extract: isProduction 13 | }), 14 | cssSourceMap: sourceMapEnabled, 15 | cacheBusting: config.dev.cacheBusting, 16 | transformToRequire: { 17 | video: ['src', 'poster'], 18 | source: 'src', 19 | img: 'src', 20 | image: 'xlink:href' 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /express-mongodb-vue/build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const config = require('../config') 5 | const vueLoaderConfig = require('./vue-loader.conf') 6 | 7 | function resolve (dir) { 8 | return path.join(__dirname, '..', dir) 9 | } 10 | 11 | 12 | 13 | module.exports = { 14 | context: path.resolve(__dirname, '../'), 15 | entry: { 16 | app: './src/main.js' 17 | }, 18 | output: { 19 | path: config.build.assetsRoot, 20 | filename: '[name].js', 21 | publicPath: process.env.NODE_ENV === 'production' 22 | ? config.build.assetsPublicPath 23 | : config.dev.assetsPublicPath 24 | }, 25 | resolve: { 26 | extensions: ['.js', '.vue', '.json'], 27 | alias: { 28 | 'vue$': 'vue/dist/vue.esm.js', 29 | '@': resolve('src'), 30 | } 31 | }, 32 | module: { 33 | rules: [ 34 | { 35 | test: /\.vue$/, 36 | loader: 'vue-loader', 37 | options: vueLoaderConfig 38 | }, 39 | { 40 | test: /\.js$/, 41 | loader: 'babel-loader', 42 | include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] 43 | }, 44 | { 45 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 46 | loader: 'url-loader', 47 | options: { 48 | limit: 10000, 49 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 50 | } 51 | }, 52 | { 53 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, 54 | loader: 'url-loader', 55 | options: { 56 | limit: 10000, 57 | name: utils.assetsPath('media/[name].[hash:7].[ext]') 58 | } 59 | }, 60 | { 61 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 62 | loader: 'url-loader', 63 | options: { 64 | limit: 10000, 65 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 66 | } 67 | }, 68 | { 69 | test: /\.scss$/, 70 | loaders: ['style', 'css', 'sass'] 71 | } 72 | ] 73 | }, 74 | node: { 75 | // prevent webpack from injecting useless setImmediate polyfill because Vue 76 | // source contains it (although only uses it if it's native). 77 | setImmediate: false, 78 | // prevent webpack from injecting mocks to Node native modules 79 | // that does not make sense for the client 80 | dgram: 'empty', 81 | fs: 'empty', 82 | net: 'empty', 83 | tls: 'empty', 84 | child_process: 'empty' 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /express-mongodb-vue/build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const utils = require('./utils') 3 | const webpack = require('webpack') 4 | const config = require('../config') 5 | const merge = require('webpack-merge') 6 | const path = require('path') 7 | const baseWebpackConfig = require('./webpack.base.conf') 8 | const CopyWebpackPlugin = require('copy-webpack-plugin') 9 | const HtmlWebpackPlugin = require('html-webpack-plugin') 10 | const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 11 | const portfinder = require('portfinder') 12 | 13 | const HOST = process.env.HOST 14 | const PORT = process.env.PORT && Number(process.env.PORT) 15 | 16 | const devWebpackConfig = merge(baseWebpackConfig, { 17 | module: { 18 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) 19 | }, 20 | // cheap-module-eval-source-map is faster for development 21 | devtool: config.dev.devtool, 22 | 23 | // these devServer options should be customized in /config/index.js 24 | devServer: { 25 | clientLogLevel: 'warning', 26 | historyApiFallback: { 27 | rewrites: [ 28 | { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') }, 29 | ], 30 | }, 31 | hot: true, 32 | contentBase: false, // since we use CopyWebpackPlugin. 33 | compress: true, 34 | host: HOST || config.dev.host, 35 | port: PORT || config.dev.port, 36 | open: config.dev.autoOpenBrowser, 37 | overlay: config.dev.errorOverlay 38 | ? { warnings: false, errors: true } 39 | : false, 40 | publicPath: config.dev.assetsPublicPath, 41 | proxy: config.dev.proxyTable, 42 | quiet: true, // necessary for FriendlyErrorsPlugin 43 | watchOptions: { 44 | poll: config.dev.poll, 45 | } 46 | }, 47 | plugins: [ 48 | new webpack.DefinePlugin({ 49 | 'process.env': require('../config/dev.env') 50 | }), 51 | new webpack.HotModuleReplacementPlugin(), 52 | new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. 53 | new webpack.NoEmitOnErrorsPlugin(), 54 | // https://github.com/ampedandwired/html-webpack-plugin 55 | new HtmlWebpackPlugin({ 56 | filename: 'index.html', 57 | template: 'index.html', 58 | inject: true 59 | }), 60 | // copy custom static assets 61 | new CopyWebpackPlugin([ 62 | { 63 | from: path.resolve(__dirname, '../static'), 64 | to: config.dev.assetsSubDirectory, 65 | ignore: ['.*'] 66 | } 67 | ]) 68 | ] 69 | }) 70 | 71 | module.exports = new Promise((resolve, reject) => { 72 | portfinder.basePort = process.env.PORT || config.dev.port 73 | portfinder.getPort((err, port) => { 74 | if (err) { 75 | reject(err) 76 | } else { 77 | // publish the new Port, necessary for e2e tests 78 | process.env.PORT = port 79 | // add port to devServer config 80 | devWebpackConfig.devServer.port = port 81 | 82 | // Add FriendlyErrorsPlugin 83 | devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ 84 | compilationSuccessInfo: { 85 | messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], 86 | }, 87 | onErrors: config.dev.notifyOnErrors 88 | ? utils.createNotifierCallback() 89 | : undefined 90 | })) 91 | 92 | resolve(devWebpackConfig) 93 | } 94 | }) 95 | }) 96 | -------------------------------------------------------------------------------- /express-mongodb-vue/build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const path = require('path') 3 | const utils = require('./utils') 4 | const webpack = require('webpack') 5 | const config = require('../config') 6 | const merge = require('webpack-merge') 7 | const baseWebpackConfig = require('./webpack.base.conf') 8 | const CopyWebpackPlugin = require('copy-webpack-plugin') 9 | const HtmlWebpackPlugin = require('html-webpack-plugin') 10 | const ExtractTextPlugin = require('extract-text-webpack-plugin') 11 | const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 12 | const UglifyJsPlugin = require('uglifyjs-webpack-plugin') 13 | 14 | const env = require('../config/prod.env') 15 | 16 | const webpackConfig = merge(baseWebpackConfig, { 17 | module: { 18 | rules: utils.styleLoaders({ 19 | sourceMap: config.build.productionSourceMap, 20 | extract: true, 21 | usePostCSS: true 22 | }) 23 | }, 24 | devtool: config.build.productionSourceMap ? config.build.devtool : false, 25 | output: { 26 | path: config.build.assetsRoot, 27 | filename: utils.assetsPath('js/[name].[chunkhash].js'), 28 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') 29 | }, 30 | plugins: [ 31 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 32 | new webpack.DefinePlugin({ 33 | 'process.env': env 34 | }), 35 | new UglifyJsPlugin({ 36 | uglifyOptions: { 37 | compress: { 38 | warnings: false 39 | } 40 | }, 41 | sourceMap: config.build.productionSourceMap, 42 | parallel: true 43 | }), 44 | // extract css into its own file 45 | new ExtractTextPlugin({ 46 | filename: utils.assetsPath('css/[name].[contenthash].css'), 47 | // Setting the following option to `false` will not extract CSS from codesplit chunks. 48 | // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack. 49 | // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 50 | // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110 51 | allChunks: true, 52 | }), 53 | // Compress extracted CSS. We are using this plugin so that possible 54 | // duplicated CSS from different components can be deduped. 55 | new OptimizeCSSPlugin({ 56 | cssProcessorOptions: config.build.productionSourceMap 57 | ? { safe: true, map: { inline: false } } 58 | : { safe: true } 59 | }), 60 | // generate dist index.html with correct asset hash for caching. 61 | // you can customize output by editing /index.html 62 | // see https://github.com/ampedandwired/html-webpack-plugin 63 | new HtmlWebpackPlugin({ 64 | filename: config.build.index, 65 | template: 'index.html', 66 | inject: true, 67 | minify: { 68 | removeComments: true, 69 | collapseWhitespace: true, 70 | removeAttributeQuotes: true 71 | // more options: 72 | // https://github.com/kangax/html-minifier#options-quick-reference 73 | }, 74 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin 75 | chunksSortMode: 'dependency' 76 | }), 77 | // keep module.id stable when vendor modules does not change 78 | new webpack.HashedModuleIdsPlugin(), 79 | // enable scope hoisting 80 | new webpack.optimize.ModuleConcatenationPlugin(), 81 | // split vendor js into its own file 82 | new webpack.optimize.CommonsChunkPlugin({ 83 | name: 'vendor', 84 | minChunks (module) { 85 | // any required modules inside node_modules are extracted to vendor 86 | return ( 87 | module.resource && 88 | /\.js$/.test(module.resource) && 89 | module.resource.indexOf( 90 | path.join(__dirname, '../node_modules') 91 | ) === 0 92 | ) 93 | } 94 | }), 95 | // extract webpack runtime and module manifest to its own file in order to 96 | // prevent vendor hash from being updated whenever app bundle is updated 97 | new webpack.optimize.CommonsChunkPlugin({ 98 | name: 'manifest', 99 | minChunks: Infinity 100 | }), 101 | // This instance extracts shared chunks from code splitted chunks and bundles them 102 | // in a separate chunk, similar to the vendor chunk 103 | // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk 104 | new webpack.optimize.CommonsChunkPlugin({ 105 | name: 'app', 106 | async: 'vendor-async', 107 | children: true, 108 | minChunks: 3 109 | }), 110 | 111 | // copy custom static assets 112 | new CopyWebpackPlugin([ 113 | { 114 | from: path.resolve(__dirname, '../static'), 115 | to: config.build.assetsSubDirectory, 116 | ignore: ['.*'] 117 | } 118 | ]) 119 | ] 120 | }) 121 | 122 | if (config.build.productionGzip) { 123 | const CompressionWebpackPlugin = require('compression-webpack-plugin') 124 | 125 | webpackConfig.plugins.push( 126 | new CompressionWebpackPlugin({ 127 | asset: '[path].gz[query]', 128 | algorithm: 'gzip', 129 | test: new RegExp( 130 | '\\.(' + 131 | config.build.productionGzipExtensions.join('|') + 132 | ')$' 133 | ), 134 | threshold: 10240, 135 | minRatio: 0.8 136 | }) 137 | ) 138 | } 139 | 140 | if (config.build.bundleAnalyzerReport) { 141 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 142 | webpackConfig.plugins.push(new BundleAnalyzerPlugin()) 143 | } 144 | 145 | module.exports = webpackConfig 146 | -------------------------------------------------------------------------------- /express-mongodb-vue/config/db.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | mongodb : "mongodb://localhost:27017/hero" 3 | } 4 | 5 | 6 | -------------------------------------------------------------------------------- /express-mongodb-vue/config/dev.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | const merge = require('webpack-merge') 3 | const prodEnv = require('./prod.env') 4 | 5 | module.exports = merge(prodEnv, { 6 | NODE_ENV: '"development"' 7 | }) 8 | -------------------------------------------------------------------------------- /express-mongodb-vue/config/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | // Template version: 1.3.1 3 | // see http://vuejs-templates.github.io/webpack for documentation. 4 | 5 | const path = require('path') 6 | 7 | module.exports = { 8 | dev: { 9 | 10 | // Paths 11 | assetsSubDirectory: 'static', 12 | assetsPublicPath: '/', 13 | proxyTable: { 14 | '/api': { 15 | target: 'http://localhost:3000', 16 | changeOrigin: true, 17 | } 18 | }, 19 | 20 | // Various Dev Server settings 21 | host: 'localhost', // can be overwritten by process.env.HOST 22 | port: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined 23 | autoOpenBrowser: false, 24 | errorOverlay: true, 25 | notifyOnErrors: true, 26 | poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- 27 | 28 | 29 | /** 30 | * Source Maps 31 | */ 32 | 33 | // https://webpack.js.org/configuration/devtool/#development 34 | devtool: 'cheap-module-eval-source-map', 35 | 36 | // If you have problems debugging vue-files in devtools, 37 | // set this to false - it *may* help 38 | // https://vue-loader.vuejs.org/en/options.html#cachebusting 39 | cacheBusting: true, 40 | 41 | cssSourceMap: true 42 | }, 43 | 44 | build: { 45 | // Template for index.html 46 | index: path.resolve(__dirname, '../dist/index.html'), 47 | 48 | // Paths 49 | assetsRoot: path.resolve(__dirname, '../dist'), 50 | assetsSubDirectory: 'static', 51 | assetsPublicPath: '/', 52 | 53 | /** 54 | * Source Maps 55 | */ 56 | 57 | productionSourceMap: true, 58 | // https://webpack.js.org/configuration/devtool/#production 59 | devtool: '#source-map', 60 | 61 | // Gzip off by default as many popular static hosts such as 62 | // Surge or Netlify already gzip all static assets for you. 63 | // Before setting to `true`, make sure to: 64 | // npm install --save-dev compression-webpack-plugin 65 | productionGzip: false, 66 | productionGzipExtensions: ['js', 'css'], 67 | 68 | // Run the build command with an extra argument to 69 | // View the bundle analyzer report after build finishes: 70 | // `npm run build --report` 71 | // Set to `true` or `false` to always turn it on or off 72 | bundleAnalyzerReport: process.env.npm_config_report 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /express-mongodb-vue/config/prod.env.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | module.exports = { 3 | NODE_ENV: '"production"' 4 | } 5 | -------------------------------------------------------------------------------- /express-mongodb-vue/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 |{{name}}
13 |{{explain}}
15 |账号:ruiwei88888@163.com密码:123456
18 | 19 |