Giter Club home page Giter Club logo

koa-web-kit's Introduction

koa-web-kit

npm Building Status node Dependency Status code style: prettier

🚀A Modern, Production-Ready, and Full-Stack Node Web Framework

Release Notes, An Introduction for koa-web-kit

This readme is for v3(require node >= 16), if you need SASS/SCSS support, use v2.x

Features

  • ✨Built with all modern frameworks and libs, including Koa, React(like Vue?)...
  • 📦Get all the Node.JS full stack development experience out of the box
  • 🔥Hot Module Replacement support, and bundle size analyzer report
  • 📉Async/Await support for writing neat async code
  • 💖Great style solutions: Styled-Components, TailwindCSS, CSS Modules
  • 🎉Simple API Proxy bundled, no complex extra reverse proxy configuration
  • 🌈Available for generating static site, also with SSR support
  • ⚡️Just one npm command to deploy your app to production
  • 🐳Docker support(dev and prod Dockerfile)
  • 👷Continuously Maintaining🍻

Quick Start

Get the latest version, and go to your project root, Also available on npm.

Before start, copy the config/app-config.js.sample to app-config.js(to project root or config dir) for local dev configuration

  1. Install Dependencies
npm install
  1. Start Dev Server

npm run dev to start koa with HMR enabled, or npm run dev:ssr to start dev server with SSR enabled(yet HMR will be disabled for now)

  1. Go to http://localhost:3000 to view the default react page

Project Structure

  • __tests__ dir, for your tests
  • mocks dir, for your mock json server and other mock data
  • api dir, the API Proxy utility, also put your api urls in api-config.js for universal import across your app
  • config dir, all webpack build configs are put here, besides, some application-wide env configs getter utilities
  • services dir, some middleware here, default logger utility also located here
  • routes dir, put your koa app routes here
  • src dir, all your front-end assets, react components, modules, etc...
  • utils dir, utilities for both node.js and front-end
  • views dir, your view templates(NOTE: when SSR is enabled, it will use the template literal string)
  • build dir, all built assets for your project, git ignored
  • logs dir, logs are put here by default, git ignored
  • All other files in project root, which indicate their purposes clearly😀.

Application Config and Environment Variables

Every project has some configuration or environment variables to make it run differently in different environments, for koa-web-kit, it also provides different ways to configure your ENVs.

app-config.js/app-config.js.sample

The pre bundled file config/app-config.js.sample lists some common variables to use in the project, you should copy and rename it to app-config.js for your local config, both put it in ${project_root} or the same config dir are supported:

module.exports = {
  //http server listen port
  "PORT": 3000,
  //most commonly used env
  "NODE_ENV": "development",
  //enable/disable built-in API Proxy
  "NODE_PROXY": true,
  //config the api proxy debug level, [0, 1, 2], 0 -> nothing, default: 1 -> simple, 2 -> verbose
  "PROXY_DEBUG_LEVEL": 1,
  //static endpoint, e.g CDN for your static assets
  "STATIC_ENDPOINT": "",
  //add a alternative prefix for your "STATIC_ENDPOINT"
  "STATIC_PREFIX": "",
  //add "/" to the end of your static url, if not existed
  "PREFIX_TRAILING_SLASH": true,
  //global prefix for your routes, e.g http://a.com/prefix/...your app routes,
  //like a github project site
  "APP_PREFIX": "",
  //customize build output dir, default ./build/app
  "OUTPUT_DIR": "",
  //if true, the "/prefix" below will be stripped, otherwise, the full pathname will be used for proxy
  "CUSTOM_API_PREFIX": true,
  //if enable HMR in dev mode, `npm run dev` will automatically enable this
  "ENABLE_HMR": true,
  //if need to enable Server Side Rendering, `npm run dev:ssr` will automatically enable this, HMR need to be disabled for now
  "ENABLE_SSR": false,
  //enable CSS Modules, should disable this when SSR is enabled for now
  "CSS_MODULES": false,
  //simple dynamic routes, based on file structure(like next.js)
  "DYNAMIC_ROUTES": false,
  //single endpoint string, multiple see below, type: <string|object>
  "API_ENDPOINTS": 'http://127.0.0.1:3001',
  //API Proxies for multiple api endpoints with different prefix in router
  "API_ENDPOINTS": {
    //set a default prefix
    "defaultPrefix": "/prefix",
    //e.g http://127.0.0.1:3000/prefix/api/login -->proxy to--> http://127.0.0.1:3001/api/login
    "/prefix": "http://127.0.0.1:3001",
    "/prefix2": "http://127.0.0.1:3002",
  }
}

Environment Variables and Configuration

All the variables in app-config.js can be set with Environment Variables, which have higher priority than app-config.js. e.g: > NODE_ENV=production npm start or

export PORT=3001
export NODE_ENV=production
npm start

You can also use .env file to config envs

Default config.default.[dev|prod].js in config dir

The project comes with default config files just like app-config.js.sample, which will be used if app-config.js above is not provided.

Priority: Environment Variables > .env > app-config.js > config.default.[dev|prod].js

Logs

The builtin services/logger.js provides some default log functionality for your app. By default, the manual log(calling like logger.info()) will be put into ./logs/app.log file, and the http requests will be put into ./logs/requests.log, both will also be logged to console. For more options, checkout the pino.

//use the default logger
const { logger, Logger } = require('../services/logger');
logger.info('message');
logger.error(new Error('test error'));
//create custom logger, log into a different file
const pino = require('pino');
//the 2nd params for the constructor is for only for pino options
const mylogger = new Logger({destination: pino.destination('./logs/my-log.log')}, {});
mylogger.info('my log message');

Production Deployment

Deploy your app to production is extremely simple with only one npm script command, you can provide couple of options for different deployment phases(e.g: install, build, start server), pm2 inside is used as node process manager.

Global installation of PM2 is not required now, we will use the locally installed pm2, but if you want to use pm2 cmd everywhere, you may still want to install it globally

Usage

npm run deploy -- [skipInstall] [skipBuild] [skipServer] The last three options are boolean values in 0(or empty, false) and 1(true).

Examples:

  • npm run deploy: no options provided, defaults to do all the tasks.
  • npm run deploy -- 1: same as npm run deploy:noinstall as an alias, this will skip the npm install --no-shrinkwrap, and just go to build and start server.
  • npm run deploy -- 1 0 1: which will only build your assets
  • npm run deploy -- 1 1 0: which will just start node server, useful when all assets were built on a different machine.

You may need to create/update the deploy.sh to meet your own needs.

Powered By

powered by jetbrains

LICENSE

MIT @ 2016-present jason

koa-web-kit's People

Contributors

jasonboy avatar snyk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-web-kit's Issues

webpack.config.node.js文件作用?

请问下,webpack.config.node.js的作用是将koa的代码压缩打包么? 如何是压缩打包,那压缩打包后,是直接启动打包后的文件么?

关于路由代理修改确认

在使用代理时,我本地有一些运行出问题,进行了下面的修改,烦请确认:
1.在routes/proxy.js中,修改
const apiProxy = new HttpClient({ endPoint, prefix });

const apiProxy = new HttpClient({ endPoint: endPoint, prefix: prefix });

2.services/HttpClient.js 方法 _finalizeRequestOptions 修改如下
`_finalizeRequestOptions(options = {}) {
let optionPrefix = options.prefix || this.options.prefix;

// TODO: a path rewrite could be better
if (isCustomAPIPrefix && optionPrefix) {
  let optionEndPoint = options.endPoint || this.options.endPoint;
  let endPointUrl = new URL(optionEndPoint);
  options.headers.host = endPointUrl.host;

  options.url = options.url.replace(new RegExp(`^${optionPrefix}`), '');

}
return options;

}`

Add dotenv support

add support for using dotenv to pass app configurations, also should be compatible with legacy app-config.js

  • API_ENDPOINTS can accept simple url string, so it can be better compatiable with dotenv
  • add dotenv support

代理返回blob对象

您好,使用您的框架,我遇到个问题: get请求,返回的数据如果是blob对象的话,代理中会对齐进行编码,前端接受到的数据 将不是一个blob对象,这个如何解决?
C46F95ADE405E7D21FA43E418881C19B

关于dev问题

这套代码有配置好开发的dev环境吗,好像yarn dev后不会监听文件的变化重新打包

exec this command npm run dev:ssr error

$ npm run dev:ssr

[email protected] dev:ssr /myhome/koa-web-kit-2.8.2
cross-env ENABLE_HMR=0 CSS_MODULES=0 ENABLE_SSR=1 npm-run-all -p watch watch:ssr start

[email protected] watch /myhome/koa-web-kit-2.8.2
webpack --watch --progress --hide-modules --config config/webpack.config.dev.js

[email protected] watch:ssr /myhome/koa-web-kit-2.8.2
npm run ssr -- --watch

[email protected] start /myhome/koa-web-kit-2.8.2
nodemon --trace-warnings server.js

[email protected] ssr /myhome/koa-web-kit-2.8.2
webpack --progress --config config/webpack.config.ssr.js "--watch"

[nodemon] 1.18.10
[nodemon] to restart at any time, enter rs
[nodemon] watching: /myhome/koa-web-kit-2.8.2/api//* /myhome/koa-web-kit-2.8.2/config//* /myhome/koa-web-kit-2.8.2/build/node//* /myhome/koa-web-kit-2.8.2/routes//* /myhome/koa-web-kit-2.8.2/utils//* /myhome/koa-web-kit-2.8.2/services//* app-config.js server.js
[nodemon] starting node --trace-warnings server.js
Using [/myhome/koa-web-kit-2.8.2/config/app-config.js] as basic app configuration
Using [/myhome/koa-web-kit-2.8.2/config/app-config.js] as basic app configuration
Using [/myhome/koa-web-kit-2.8.2/config/app-config.js] as basic app configuration
10% building 0/0 modules 0 active
webpack is watching the files…

(node:56855) DeprecationWarning: Tapable.plugin is deprecated. Use new API on .hooks instead
10% building 0/0 modules 0 active
webpack is watching the files…

10% building 0/1 modules 1 active ...ctjs/ 10% building 0/1 modules 1 active .../reactjs/koa-web-kit-2.8.2 15% building 43/73 modules 30 active ...ages/School/schoolInfo/stuPlan/index.js/myhome/koa-web-kit-2.8.2/node_modules/antd/dist/antd.css:15
body {
^

SyntaxError: Unexpected token {
at new Script (vm.js:83:7)
at createScript (vm.js:267:10)
at Object.runInThisContext (vm.js:319:10)
at Module._compile (internal/modules/cjs/loader.js:684:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:657:17)
at require (internal/modules/cjs/helpers.js:22:18)
15% building 47/73 modules 26 active ...ages/School/schoolInfo/stuPlan/index.js[nodemon] app crashed - waiting for file changes before starting...
15% building 47/90 modules 43 active .../pages/School/schoolInfo/yishu/index.js 19% building 82/111 module 16% building 50/103 modules 53 active ....2/node_modules/redux-thunk/es/index.js 20% building 85/111 modul 19% building 81/117 modules 36 active ...modules/core-js/modules/_regexp-exec.js 20% building 91/144 modul 34% building 200/234 modules 34 active ...kit-2.8.2/node_modules/ 71% after chunk graph WebAssemblyModules 34% building 201/234 modules 33 active ...kit-2.8.2/node_modules/antd/es/index.js 87% record chunks Record 34% building 204/234 modules 30 active ...kit-2.8.2/node_modules/antd 88% content hashing JavascriptModule 35% building 215/254 modules 39 active ...ol/schoolInfo/schoolView/viewContent.jsHash: 81441c461dd449737536
Version: webpack 4.28.4
Time: 2705ms
Built at: 2019/02/20 下午5:41:32
Asset Size Chunks Chunk Names
ssr.js 2.56 MiB ssr [emitted] ssr
Entrypoint ssr = ssr.js
[./build/app/manifest.json] 368 bytes {ssr} [built]
[./build/react-loadable.json] 1.55 MiB {ssr} [built]
[./src/AppRoutes.jsx] 1.52 KiB {ssr} [built]
[./src/modules/context.js] 360 bytes {ssr} [built]
[./src/pages/routes.js] 10 KiB {ssr} [built]
[./src/ssr/index.js] 5.14 KiB {ssr} [built]
[@babel/runtime/helpers/interopRequireDefault] external "@babel/runtime/helpers/interopRequireDefault" 42 bytes {ssr} [built]
[@loadable/component] external "@loadable/component" 42 bytes {ssr} [built]
[core-js/modules/web.dom.iterable] external "core-js/modules/web.dom.iterable" 42 bytes {ssr} [built]
[prop-types] external "prop-types" 42 bytes {ssr} [built]
[react] external "react" 42 bytes {ssr} [built]
[react-dom/server] external "react-dom/server" 42 bytes {ssr} [built]
[react-loadable] external "react-loadable" 42 bytes {ssr} [built]
[react-loadable/webpack] external "react-loadable/webpack" 42 bytes {ssr} [built]
[react-router-dom] external "react-router-dom" 42 bytes {ssr} [built]
+ 203 hidden modules
36% building 218/258 modules 40 active ...-2.8.2/src/components/ziliao/index.scss[nodemon] restarting due to changes...
[nodemon] starting node --trace-warnings server.js
38% building 239/282 modules 43 active ...-2.8.2/src/components/Footer/index.scssUsing [/myhome/koa-web-kit-2.8.2/config/app-config.js] as basic app configuration
68% building 591/604 modules 13 active ...2/node_modules/zrender/lib/core/util.js/myhome/koa-web-kit-2.8.2/node_modules/antd/dist/antd.css:15
body {
^

SyntaxError: Unexpected token {
at new Script (vm.js:83:7)
at createScript (vm.js:267:10)
at Object.runInThisContext (vm.js:319:10)
at Module._compile (internal/modules/cjs/loader.js:684:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:657:17)
at require (internal/modules/cjs/helpers.js:22:18)
[nodemon] app crashed - waiting for file changes before starting...nearGradient.js
95% emitting ManifestPlugin(node:56855) DeprecationWarning: Chunk.forEachModule: Use for(const module of chunk.modulesIterable) instead
Hash: aa624165a41dea2ef279
Version: webpack 4.28.4
Time: 10269ms
Built at: 2019/02/20 下午5:41:39
Asset Size Chunks Chunk Names
app.css 661 KiB app [emitted] app
app.css.map 814 KiB app [emitted] app
app.js 11.3 MiB app [emitted] app
app.js.map 11.1 MiB app [emitted] app
assets/static/favicon.ico 16.6 KiB [emitted]
assets/static/logo.svg 2.61 KiB [emitted]
favicon.ico 16.6 KiB [emitted]
index-backup.html 1.16 KiB [emitted]
manifest.json 368 bytes [emitted]
runtime.js 6.08 KiB runtime [emitted] runtime
runtime.js.map 5.98 KiB runtime [emitted] runtime
Entrypoint app = runtime.js runtime.js.map app.css app.js app.css.map app.js.map

ERROR in ./src/App.jsx
Module not found: Error: Can't resolve 'react-addons-css-transition-group' in '/myhome/koa-web-kit-2.8.2/src'
@ ./src/App.jsx 16:60-104
@ ./src/index.js
Hash: 40799cda9bbd9526a833
Version: webpack 4.28.4
Time: 109ms
Built at: 2019/02/20 下午5:41:40
Asset Size Chunks Chunk Names
ssr.js 2.56 MiB ssr [emitted] ssr
Entrypoint ssr = ssr.js
[./build/react-loadable.json] 1.55 MiB {ssr} [built]
+ 217 hidden modules
[nodemon] restarting due to changes...
[nodemon] starting node --trace-warnings server.js
Using [/myhome/koa-web-kit-2.8.2/config/app-config.js] as basic app configuration
/myhome/koa-web-kit-2.8.2/node_modules/antd/dist/antd.css:15
body {
^

SyntaxError: Unexpected token {
at new Script (vm.js:83:7)
at createScript (vm.js:267:10)
at Object.runInThisContext (vm.js:319:10)
at Module._compile (internal/modules/cjs/loader.js:684:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:657:17)
at require (internal/modules/cjs/helpers.js:22:18)
[nodemon] app crashed - waiting for file changes before starting...

命令npm run deploy 如何ssr运行?

您好
再问个问题,如果想要服务器渲染(ssr)的方式运行,应执行什么命令?

我运行了npm run deploy后,查看源码还是JS进行页面渲染的。

Better Docker support

the current Dockerfile is just some kine of demo, which is not production ready.
TODO:

  • Docker integration for local development
  • Docker integration for production deployment
  • Improve the way to pass config into docker container for both dev and prod
  • docker-compose support

报websocket的错误

有时候会报错 怎么去掉这个报错?
socket.js:19 WebSocket connection to 'ws://localhost:63065/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

yarn install 之后 ,run dev 出现了这个问题。。

(node:58220) UnhandledPromiseRejectionWarning: TypeError: res.getHeader is not a function
    at processRequest (/Users/blockmood/Desktop/pc/node_modules/webpack-dev-middleware/lib/middleware.js:82:18)
    at ready (/Users/blockmood/Desktop/pc/node_modules/webpack-dev-middleware/lib/util.js:51:12)
    at handleRequest (/Users/blockmood/Desktop/pc/node_modules/webpack-dev-middleware/lib/util.js:167:5)
    at Promise (/Users/blockmood/Desktop/pc/node_modules/webpack-dev-middleware/lib/middleware.js:44:7)
    at new Promise (<anonymous>)
    at middleware (/Users/blockmood/Desktop/pc/node_modules/webpack-dev-middleware/lib/middleware.js:43:12)
    at Promise (/Users/blockmood/Desktop/pc/node_modules/koa-webpack/lib/middleware.js:28:9)
    at new Promise (<anonymous>)
    at /Users/blockmood/Desktop/pc/node_modules/koa-webpack/lib/middleware.js:27:20
    at dispatch (/Users/blockmood/Desktop/pc/node_modules/koa/node_modules/koa-compose/index.js:42:32)
    at createGenerator (/Users/blockmood/Desktop/pc/node_modules/koa-convert/index.js:24:16)
    at createGenerator.next (<anonymous>)
    at Object.<anonymous> (/Users/blockmood/Desktop/pc/node_modules/koa-history-api-fallback/lib/index.js:104:5)
    at Generator.next (<anonymous>)
    at onFulfilled (/Users/blockmood/Desktop/pc/node_modules/co/index.js:65:19)
    at /Users/blockmood/Desktop/pc/node_modules/co/index.js:54:5
(node:58220) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:58220) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.