Preface:
This time write a small Node server architecture, using KOA +swig, gulp, jsdocs generated documentation, there is not much content to record, for the next large project architecture preparation. Attach GitHub address
Node JWT certification for the front-end architecture of large project architecture!!
1. Project Catalog
-Dist: Automatic generation, docs, config: configuration files, models: Data interaction, Web: not used yet, and tests: files to store. -dist: Automatic generation, docs, config: Configuration files, controllers, models: Data interaction, Web: not used yet, and tests: files to store. Front-end automation test Karma, Backstopjs, Selenium- WebDriver, Mocha)
2. Write gulpfile. Js
First create file gulpfile.js, realize compilation, listen to the file changes automatically compiled
Es6 NPM install -d babel-plugin-transform-es2015-modules-commonjs gulp gulp-babel gulp-watch NPM install -d cross-envCopy the code
const gulp = require('gulp')
const babel = require('gulp-babel')
const watch = require('gulp-watch'); // Production environment gulp.task('buliddev', () = > {return watch('./src/nodeuii/**/*.js'// listen on SRC /nodeuii all js {ignoreInitial:false },
() => {
gulp.src('./src/nodeuii/**/*.js'// compile this file.pipe (Babel ({babelrc:false."plugins": ["transform-es2015-modules-commonjs"]
}))
.pipe(gulp.dest('dist')); // output to dist})});let _task = ['buliddev']
if(process.env.NODE_ENV == 'production') {
_task = [];
}
gulp.task('default', _task)Copy the code
3. Write config > index. Js
// Lodash NPM install-s lodashCopy the code
import _ from 'lodash'
import path from 'path'// Static path, will be used laterlet config = {
'viewDir': path.join(__dirname, '.. /views'),
'staticDir': path.join(__dirname, '.. /assets'Const init = () => {const init = () => {if(process.env.NODE_ENV == 'development'){
const localConfig = {
port:8081
}
config = _.extend(config, localConfig)
}
if(process.env.NODE_ENV == 'production'){
const localConfig = {
port:80
}
config = _.extend(config, localConfig)
}
return config
}
const result = init()
export default resultCopy the code
4. Configure package.json and start the node with Supervisor
// Install supervisor NPM install -d SupervisorCopy the code
"scripts": {
"test": ""."server:bulid": "gulp"."start": "pm2 start"."bulid": ""."docs": "jsdoc ./src/nodeuii/**/*.js -d ./docs/jsdocs"."start:dev": "cross-env NODE_ENV=development supervisor ./dist/app.js"
},Copy the code
5. Write app. Js
// Install NPM install-s koa kao-simple-router koa-swig koa-static
Copy the code
import Koa from 'koa'
import router from 'koa-simple-router'
import render from 'koa-swig'
import serve from 'koa-static'
import co from 'co'
import config from './config'
import controllerInit from './controllers'Const app = new Koa() // config template path app.context.render = co. Wrap (render({root:config.viewDir, autoescape:true,
cache: 'memory',
ext: 'html',
varControls: ["The [["."]]"],// Change the data template style originally {{}} writeBody:false})); ControllerInit (app, router) // Configure a static path app.use(serve(config.staticdir)) console.log(config) app.listen(config.port, () => { console.log(`success listening on${config.port}`)})Copy the code
Write index.js indexController.js in controllers
index.js
import IndexController from './IndexController'Const indexController = new indexController () // Route integration centerexport default (app, router) => {
app.use(router(_ => {
_.get('/', indexController.indexHome()),
_.get('/', indexController.indexAction())
}))
}Copy the code
IndexController.js
import IndexModel from '.. /models/IndexModel'
class IndexController {
constructor() {}indexHome() {return async (ctx, next) => {
ctx.body = 'First Node Server architecture, somewhat interesting'}}indexAction() {return async (ctx, next) => {
const IndexModelIns = new IndexModel()
const result = await IndexModelIns.getData()
ctx.body = await ctx.render('index',{ data: result }); }}}export default IndexControllerCopy the code
Write indexModel.js in models
/** *@fileOverview implements the Index data model * @author Chen */ ** ** IndexModle class generates a segment of asynchronous data * @class */exportDefault class IndexModel {/** *@constructor * @example{string} app koA2 context */ constructor(app){} /** *return{Promise} returns asynchronous data * @example *return new Promise
* getData()
*/
getData() {return new Promise((resolve, reject) => {
setTimeout(function () {
resolve('Asynchronous data')}, 1000)})}}Copy the code
You can run NPM run start:dev to access 127.0.0.1:8081
If there is an error, please analyze it yourself, or continue:
6. Create folder Assets: Store static files, views: store template files
See the app.js configuration file above
css>index.css
:root{
--mainColor:#6B4C99;
}
body{
background: var(--mainColor);
}Copy the code
js>index.js
console.log(111)Copy the code
views>index.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/css/index.css">
</head>
<body>
<div id="app"> <h1>[[data]]</h1> The next... <inputtype="text" v-model="data">
{{data}}
</div>
</body>
<script src="/js/index.js"></script>
<script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
data: 'Interesting !!!! '
}
})
</script>
</html>Copy the code
You can use vue as well as swig templates.
accesshttp://127.0.0.1:8081/index
7. Generate documents
NPM install -d jsdocCopy the code
Run NPM run docs
Open index.html and the document is generated
Conclusion:
It’s almost done. It’s interesting.