Giter VIP home page Giter VIP logo

serve-my-app's Introduction

ServeMyApp

npm npm

πŸš€ Serve your Javascript application and/or add an API to it in a minute!

This package allows you to add a NodeJS Express server easily and quickly to your Javascript application.


screenshot


✨ Features:

Includes a fully customizable Express Server, which allows you to:

  • Serve your Javascript application, with routing handling.
  • Add directly your api routes into your project, without thinking to something else.

Table of contents


Getting started

In this ReadMe, we will take an example with a create-react-app application, and a @vue/cli one is coming. But it can be what you want, so please, let us know if you tested it with another framework or app. It will be added to this doc.

Installation

cd my-app
npm install serve-my-app express

Automatic initialisation

npx sma-init

Configuration

The serve-my-app binary will serve your frontend and your api.

It has several configuration parameters.

See usage section to understand how to use them.

Most useful ones:

Option Type Default value Usage
--srv string / false false Serve api routes from this folder (relative path)
--src string / false false Serve your application from this folder (browser compatible files)
--watch false false Restart server if change detected in --srv folder
--proxify boolean false Proxify calls from your app to the express server (depends of you app dev server)

Other ones:

Option Type Default value Usage
--host string HOST if set or '0.0.0.0' Specify server host
--port integer PORT if set or 3001 Specify server port
--https boolean HTTPS if set or false Specify if displayed url should use https

Usage

Automatic initialisation

You really should use the sma-init command to configure your server, but see below to understand how tu use ServeMyApp

I only want to serve my frontend code in production

  • Build your application files (depends on your application framework/type):

     npm run build
  • Serve them.

     serve-my-app --src=build

Explanation:

  • --src: We're assuming that previous command will output compiled files to build folder.

I only want to add some api routes.

  • Create an api file as described below.

  • Serve it for development purpose:

    serve-my-app --srv=srv --watch
  • Add your routes

  • Serve it for production:

    serve-my-app --srv=srv

Explanation:

  • --srv: We're assuming that your api entrypoint is in srv folder.
  • --watch: Server will restart when a route will be added.

I want to serve both my frontend code and add some api routes.

Then :

  • For development purpose:

    • Launch the server

        serve-my-app --srv=srv --proxify --watch
    • Launch your frontend application (depends on your framework):

      npm run start/serve

    Explanation:

    • --srv: We're assuming that your api entrypoint is in srv folder.
    • --watch: Server will restart when a route will be added.
    • --proxify: All the relative xhr/fetch calls made in the application will be proxyfied to the server.
  • To run the server only once for production:

    • Build your app files (depends on your framework):

      npm run build
    • Launch the server

      serve-my-app --srv=srv --src=build

    Explanation:

    • --srv: We're assuming that your api entrypoint is in srv folder.
    • --src: We're assuming that previous command will output compiled files to build folder.

πŸ‘ In all cases, you can use relative urls for xhr/fetch calls in your code. πŸš€ Again, all the ServeMyApp related commands and files can be generated using the sma-init cli tool.

FAQ

What should the server entrypoint look like?

It's a file exporting a function, which will receive the Express application as its first parameter, and the node http server as its second. With both you can do anything you want with your server.

For example:

const { json } = require('express');
const socketIO = require("socket.io");

module.export = (app, http) => {
    app.use(json());

    app.get('/foo', (req, res) => {
        res.json({msg: 'foo'});
    });

    app.post('/bar', (req, res) => {
        res.json(req.body);
    });
    
    socketIO(http).on("connection", client => {
      client.emit("message", "Welcome");
     });
}

I want to use some transpilation process for my server (Webpack, TypeScript...).

And you're right, it's a good idea!

In that case, you just have to handle the compilation process on your own, and specify an other folder for β€”srv files.

For example, for a TypeScript transpilation, and an "outDir": "../dist" in srv/tsconfig.json, you can update your script in package.json as:

"build:server": "rm -rf dist && tsc -p srv",
"sma": "serve-my-app --srv=dist [...]"

🀘 For Typescript transpilation ts-node will be used if your api entrypoint is detected as a typescript file. It allows you to use directly your typescript file for development:

"sma:dev": "serve-my-app --srv=srv --watch [...]"

πŸ˜‰ To help you in your Typescript development, you can import the ApiFunction type from 'serve-my-app':

import { ApiFunction } from 'serve-my-app'

const api: ApiFunction = (app, server) => {
 //
}

export default api

πŸ”— See a full example at: mathieutu/starter-kit-react-express

My package.json behaves in a weird manner: a proxy key comes and goes in it.

To proxify xhr calls from the front dev server to the express server, create-react-app uses a proxy key in the package.json. This is why this package adds it automatically if --proxify argument is provided.

This should be transparent for you, but if you want to disable it and handle yourself (or not) the proxy, you can do it by not passing the -β€”proxify flag.

You can find the documentation about proxies in create-react-app here.

Another question?

Please feel free to ask it!

License

This package is an open-sourced software licensed under the MIT license.

Contributing

Issues and PRs are obviously welcomed and encouraged, for new features as well as documentation.

serve-my-app's People

Contributors

mathieutu avatar temsa avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

temsa

serve-my-app's Issues

Cannot find module 'xxx/srv

$ serve-my-app --src=.vuepress/dist
(node:33998) UnhandledPromiseRejectionWarning: Error: Cannot find module '/Users/mathieutu/Projects/mathieutu.dev/srv'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.resolve (internal/modules/cjs/helpers.js:30:19)
    at isTypescriptFile (/Users/mathieutu/Projects/mathieutu.dev/node_modules/serve-my-app/dist/utils/paths.js:29:49)
    at Object.exports.load (/Users/mathieutu/Projects/mathieutu.dev/node_modules/serve-my-app/dist/utils/paths.js:34:9)
    at Object.<anonymous> (/Users/mathieutu/Projects/mathieutu.dev/node_modules/serve-my-app/dist/run.js:27:29)
    at Generator.next (<anonymous>)
    at fulfilled (/Users/mathieutu/Projects/mathieutu.dev/node_modules/serve-my-app/dist/run.js:4:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at startup (internal/bootstrap/node.js:283:19)
(node:33998) 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:33998) [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.

Add tests

This project need tests. My knowledge in Javascript testing is quite limited, so help is very welcomed!

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.