大前端学习第5课: Koa项目工程化2

1,056 阅读2分钟

在前面的课程中,简单的配置了一下webpack,以及介绍了一些nodejs的调试技巧。这节课信息量还是比较大的。主要讲了以下内容:

目录

  1. npm-check-updates的使用
  2. koa-compose的使用
  3. 如何分离webpack的生成环境和开发环境
  4. Terser的使用
  5. 生产环境中,koa的目录结构
  6. Koa-compress的使用

npm-check-updates

Find newer versions of dependencies than what your package.json or bower.json allows 查找package.json更新的依赖项

使用很简单。

安装: npm install npm-check-updates -g

升级:ncu -u

删除:rm -rf node_modules

安装:npm install

koa-compose

Compose Koa middleware : 组装koa的中间件

install: npm i koa-compose

// 这种写法将被淘汰
app.use(helmet());
app.use(statics(path.join(__dirname, '../public')));
app.use(router());
// 使用compose
const middleware = compose([
  koaBody(),
  statics(path.join(__dirname, '../public')),
  cors(),
  jsonutil({ pretty: false, param: 'pretty' }),
  helmet()
])

app.use(middleware);
app.use(router());

如何分离webpack的生成环境和开发环境

通常来说,webpack的配置文件会有3个。分别是:

  1. webpack.config.base.js
  2. webpack.config.dev.js
  3. webpack.config.prod.js

首先: webpack.config.base.js里面的内容见我的 另外一篇博客.

配置definePlugin

The DefinePlugin allows you to create global constants which can be configured at compile time. DefinePlugin允许您创建可在编译时配置的全局常量。

// webpack.config.base.js
import webpack from 'webpack';
plugin: [
  new CleanWebpackPlugin(),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod') ? "'production'" : "'development'"
    }
  })
],

使用webpack-merge合并webpack配置

Variant of merge that's useful for webpack configuration: 它对合并webpack的变量很有用。

// webpack.config.dev.js
const webpaceMerge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.config.base');

const webpackConfig = {
  mode: 'development',
  devtool: 'eval-source-map',
  status: { children: false }
}

module.exports = webpaceMerge(baseWebpackConfig, webpackConfig);

使用Terser压缩文件

This plugin uses terser to minify your JavaScript.

webpack4建议使用terser

使用: npm install terser-webpack-plugin

const webpaceMerge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.config.base');
const terserWebpackPlugin = require('terser-webpack-plugin');


const webpackConfig = webpaceMerge(baseWebpackConfig, {
  mode: "production",
  stats: { children: fasle, warnings: false },
  optimization: {
    minimizer: [
      new terserWebpackPlugin({
        terserOptions: {
          warnings: false,
          compress: {
            warnings: false,
            drop_console: false,
            dead_code: true,
            drop_debugger: true
          },
          output: {
            comments: false,
            beautify: false,
          },
          mangle: true,
        },
        parallel: true,
        sourceMap: false
      })
    ]
  }
})

module.exports = webpackConfig;

使用spilitChunks

Originally, chunks (and modules imported inside them) were connected by a parent-child relationship in the internal webpack graph. The CommonsChunkPlugin was used to avoid duplicated dependencies across them, but further optimizations were not possible. spilitChunks 可以避免重复依赖

splitChunks: {
  cacheGroups: {
    commons: {
      name: 'commons',
      chunks: 'initial',
      minChunks: 3
    }
  }
}

使用utils配置path

const path = require('path')

exports.resolve = function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

exports.APP_PATH = exports.resolve('src')
exports.DIST_PATH = exports.resolve('dist')

最后, 配置package.json

"scripts": {
    "start": "nodemon src/index.js",
    "start:es6": "nodemon --exec babel-node src/index.js",
    "build": "cross-env NODE_ENV=prod webpack --config config/webpack.config.prod.js",
    "dev": "cross-env NODE_ENV=dev nodemon --exec babel-node --inspect ./src/index.js",
    "clean": "rimraf dist"
  },

rimraf: 删除dist目录,类似rm -rf

生产环境中,koa的目录结构

// api=> demoController.js
class DemoController {
  constructor() { }
  async demo(ctx) {
    ctx.body = {
      msg: 'body message!!!',
    }
  }
}

export default new DemoController()
//demoRorouter.js
import Router from 'koa-router';
import demoController from '../api/demoController';

const router = new Router();

router.get('/demo', demoController.demo);

export default router;
// routes.js
import combineRoutes from 'koa-combine-routers'

import demoRouter from './demoRouter'

export default combineRoutes(demoRouter)

Koa Compress

Compress middleware for Koa: koa的压缩中间件

import compress from 'koa-compress';
//index.js
if(!isDevMode) {
  app.use(compress())
}

我是海明月,前端小学生。