简单了解前端模块化

613 阅读1分钟

前言

前端模块化,真的是一个不错的知识点,尽管如今的面试已经很少会提到了,但是有极个别的公司还是会问的。这里简单分享一下。

方案

前端模块化的方案挺多的,比如amd,cmd,commonjs,umd,es modules。

amd

amd也叫异步模块定义。requirejs实现了这个模块规范。

define(['util'], function (util) {
  util.isEmpty('aaa')
})

cmd

cmd也叫通用模块定义。requirejs和seajs都实现了这个模块规范。

define(function (require, exports, module) {
  var $ = require('jquery.js')
  $('div').addClass('active')
})

commonjs

commonjs应用于nodejs。

var fs = require('fs')
fs.readFile('name.txt', function (err, data) {
  if (err) {
    console.log(err)
    return
  }
  console.log(data.toString())
})

umd

umd类似于兼容commonjs和amd的语法糖,是模块定义的跨平台解决方案。

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['b'], factory)
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(require('b'))
  } else {
    // Browser globals (root is window)
    root.returnExports = factory(root.b)
  }
}(this, function (b) {
  //use b in some fashion.

  // Just return a value to define the module export.
  // This example returns an object, but the module
  // can return a function as the exported value.
  return {}
}))

es modules

es modules是JavaScript官方的标准化模块系统。

import Koa from 'koa'
import KoaRouter from 'koa-router'
import KoaOnerror from 'koa-onerror'
import KoaBodyparser from 'koa-bodyparser'
import KoaLogger from 'koa-logger'
import KoaJwt from 'koa-jwt'
import Routers from './core/routers.js'
import jwtConfig from './config/jwt.config.js'

const app = new Koa()
// KoaOnerror(app,{
//     all(ctx){
//         console.log('系统异常')
//         ctx.body = '系统异常'
//     }
// })
const koaRouter = KoaRouter()

// 中间件 https://www.cnblogs.com/LChenglong/p/12118666.html
// koa-onerror
// koa-router
// koa-bodyparser
// koa-multer
// koa-session
// koa-jwt
// koa-compress
// koa-helmet
// koa-logger
// koa2-cors

// 数据库
// mongoose http://www.mongoosejs.net/docs/index.html

// 用户权限 
// https://www.cnblogs.com/pl-boke/p/10063351.html 
// https://www.cnblogs.com/swordfall/p/10841418.html

app.use(KoaLogger())

// Custom 401 handling if you do not want to expose koa-jwt errors to users
app.use(function (ctx, next) {
    return next().catch((err) => {
        if (401 == err.status) {
            ctx.status = 401
            ctx.body = {
                code: 0,
                err: {
                    info: `Protected resource, use Authorization header to get access\n`
                }
            }
        } else {
            throw err
        }
    })
})

app.use(KoaJwt({ secret: jwtConfig.secret }).unless({
    path: [/^\/usersControllers\/login/]
}))
app.use(KoaBodyparser())


Object.keys(Routers).map(item => {
    Object.keys(Routers[item]).map(itm => {
        const { type, fn } = Routers[item][itm]
        koaRouter[type](`/${item}/${itm}`, fn)
    })
})
app.use(koaRouter.routes())
app.use(koaRouter.allowedMethods())

export default app

谢谢阅读!