Git Product home page Git Product logo

backpack's Introduction

backpack

backpack-status npm version Discord

Backpack is minimalistic build system for Node.js. Inspired by Facebook's create-react-app, Zeit's Next.js, and Remy's Nodemon, Backpack lets you create modern Node.js apps and services with zero configuration. Backpack handles all the file-watching, live-reloading, transpiling, and bundling, so you don't have to. It comes with a few conventions defaults (like support for the latest JavaScript awesomeness (i.e. async/await, object rest spread, and class properties)), but everything can be customized to fit your project's needs. Best of all, you can easily add Backpack to your existing Node.js project with just a single dependency.

Backpack comes with the "battery-pack included":

  • Latest ES6 features (including module syntax, async/await, object rest spread)
  • SUPER friendly, human readable error messages
  • Live reload (on saves, add/delete file, etc.)
  • Zero-config, one dependency.

HOWEVER, you can configure Backpack to your project's needs by extending the underlying Webpack 4 configuration.

PLEASE READ: If you're thinking of using Backpack with React.js, you should use Razzle instead. It is a project purpose-built for SSR React with an almost identical API.

Table of Contents

How to use

Install it:

npm i backpack-core --save

and add a script to your package.json like this:

{
  "scripts": {
    "dev": "backpack"
  }
}

After that there are just a few conventions defaults:

  • src/index.js: the entry of your app.

...actually that's it.

You can then run your application in development mode:

npm run dev

Successful builds will show a console like this. Note: screenshot taken from running the basic example npm run dev

Custom configuration

For custom advanced behavior, you can create a backpack.config.js in the root of your project's directory (next to package.json).

// backpack.config.js
// IMPORTANT: This file is not going through babel transformation.
// You can however use the ES2015 features supported by your Node.js version.
module.exports = {
  /* config options here */
};

Customizing webpack config

Example

To extend webpack, you can define a function that extends its config via backpack.config.js.

// backpack.config.js
module.exports = {
  webpack: (config, options, webpack) => {
    // Perform customizations to config
    // Important: return the modified config
    return config;
  },
};

Customizing babel config

Example

To extend our usage of babel, you can define a .babelrc file at the root of your app. This file is optional.

If found, Backpack will consider it to be the source of truth. Thus it must define what Backpack needs as well, which is the backpack-core/babel preset.

This is designed so that you are not surprised by modifications we could make to the default babel configurations.

Here's an example .babelrc file:

{
  "presets": [
    "backpack-core/babel",
    "stage-0"
  ]
}

Note: This works exactly like Next.js does.

Building for Production

Add a npm script for the build step:

{
  "scripts": {
    "dev": "backpack",
    "build": "backpack build"
  }
}

Then run the build command and start your app

npm run build
node ./build/main.js

CLI Commands

backpack dev

Runs backpack in development mode.

Your code will reload if you make edits.
You will see the build errors in the console that look like this.

backpack dev

backpack build

Builds the app for production to the build folder.
It correctly bundles your production mode and optimizes the build for the best performance.

You can run your production application with the following command:

node ./build/main.js

Your application is ready to be deployed!

Note: Make sure to add the build directory to your .gitignore to keep compiled code out of your git repository

FAQ

Is this like Create-React-App or Next.js?

Yes and No.

Yes in that they will all make your life easier.

No in that it that Backpack is focused on server-only applications. You should use create-react-app or Next.js for your frontend and then build your backend with Backpack.

Can I use this with React to build a universal app?

Technically, yes. However, we strongly advise against it at the moment. Backpack handles file-watching and reloading in a way that will make things like webpack-hot-middleware annoying to work with.

What syntactic features are transpiled? How do I change them?

We track V8. Since V8 has wide support for ES6, we don't transpile it. Since V8 doesn’t support async/await and class properties yet, we transpile those.

See this and this

Why is it called Backpack?

Backpack is focused on server-only applications. We've been using it for building out Node.js backends and microservices. Under the hood, Webpack and a few other tools make the magic happen. Hence Backend + Webpack = Backpack.

Inspiration

Authors

backpack's People

Contributors

amonks avatar andres-valdes avatar biigpongsatorn avatar cyruseftos avatar despairblue avatar ericclemmons avatar evenfrost avatar fengzilong avatar ganapativs avatar j12934 avatar jacopkane avatar jaredpalmer avatar leonardosnt avatar ljukas avatar mattleff avatar nayni avatar nkohari avatar pi0 avatar pradel avatar robertyoung avatar shrynx avatar sompylasar avatar tobiaslins avatar xouabita 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  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

backpack's Issues

Nodemon configuration does not allow for white spaces

I'm currently running into the same issue as issue #59, where backpack cannot run because there are white spaces in the directory where I am executing the command. Please note that I'm running Windows 10.

I have reason to believe that the way that you configured Nodemon to run is at fault.

const startServer = () => {
  const serverPaths = Object
    .keys(serverCompiler.options.entry)
    .map(entry => path.join(serverCompiler.options.output.path, `${entry}.js`))
  nodemon({ script: serverPaths[0], watch: serverPaths, nodeArgs: process.argv.slice(2) })
    .on('quit', process.exit)
}

If I hardcode nodemon to use './build/main', instead of serverPaths[0], everything works fine. I could create a pull request but I'm not sure if that's the most elegant solution.

Inherit flag options from Webpack

Would it be possible to inherit original flag options from Webapck? Such as use --config to customise configuration files, use -p,--bail and more to configure production build?

exit code is 0 when build failed

When the build fails the exit code of backpack is 0.

That makes it necessary to capture backpacks output and parse it to use it in a CI.

[RFC] Add support for rollup and taskr

#showerthoughts...

Rollup and Taskr (formerly Fly) have come a long way since Backpack launched. It would be great to support both.

Why?

There is a lot to be said for zero config. A LOT. Just getting taskr and rollup setup, even for experienced devs, can take 15-30 minutes.

backpack.config.js might look like:

// backpack.config.js for rollup

const alias = require('rollup-plugin-alias')
const path = require('path')

module.exports = {
   modifyRollupConfig: (config, options, rollup) => {
    config.plugins.push(alias({
       common: path.join(__dirname, './src/common') . // can now import common from 'common'
    }))

     return config
   }
}
// backpack.config.js for taskr
module.exports =  {
   modifyTaskrConfig: (config, options) => {
      config.lint = async function (task) {
        await task.source('src/*.js') // etc...
      }
      return config
   }
}

How to add NODE_PATH to in package.json?

How do I add NODE_PATH in package.json?

Part of my packcage.json:

   "dependencies": {
       "axios": "^0.16.2",
       "cross-env": "^5.0.1",
       "koa": "^2.3.0",
       "koa-mount": "^3.0.0",
       "koa-static": "^4.0.1",
       "koa-trie-router": "^2.1.5",
       "mongodb": "^2.2.31",
       "nuxt": "^1.0.0-rc3",
       "socket.io": "^2.0.3"
     },
     "devDependencies": {
       "babel-eslint": "^7.2.3",
       "backpack-core": "^0.4.1"
     },
     "scripts": {
       "test": "mocha --harmony",
       "dev": "NODE_PATH=./app backpack dev",
       "build": "nuxt build && backpack build",
       "start": "cross-env NODE_ENV=production NODE_PATH=./app node build/main.js"
     },

backpack.config.js:

    module.exports = {
      webpack: (config, options, webpack) => {
        config.entry.main = './server/index.js'
        return config
      }
    }

In my server.js:

    import Koa from 'koa'
    import { Nuxt, Builder } from 'nuxt'
    import socket from 'socket.io'
    import http from 'http'
    import config from 'config' // this is './config' without NODE_PATH=./app

Error at npm run dev:

This dependency was not found:

* config in ./server/index.js

But if I run npm start, it is working fine.

Any ideas?

Webpack alias doesn't work

Hi there, I tried to alias through webpack but it doesn't seem to work. Here's my config

backpack.config.js

module.exports = {
  webpack: (config) => {
    config.resolve.alias = {
      "react": "preact-compat"
    }
    return config
  }
}

Please take a look at it, Thanks!

Using backpack for libraries, without a index.js file?

Hey, thank you for a great project!

I wanted ask if it's possible to use backpack when developing a library, i.e. just use it to compile the code and not try to run it and build all files as single files. If it's not possible, would it be possible to add that in the future or is that outside of backpack's scope?

Thanks

CommonJS-Modules containing an async function are empty when required

Hi,

I just started to integrate backpack and it seems quite nice, but I encountered the following problem:

When a CommonJS module with an async function is required, the imported object is empty.

Test case:

a.js

exports.x = () => 5 // normal function

b.js

exports.x = async () => 5 // async function

c.js

export const x = async () => 5 // async function

index.js

const a = require('./a')
const b = require('./b')
import {x} from './c'

console.log('a', a) // normal function in CommonJS module ==> works
console.log('b', b) // async function in CommonJS module  ==> doesn't work
console.log('c', x) // async function in ES6 module       ==> works

Output

a { x: [Function] }
b {}
c function x() {
    return _ref.apply(this, arguments);
  }

Notice that the object after b is empty, so the exported functions are not callable. Strange is that the aysnc function works when imported from an ES6 module.

Don't go fullscreen when building

It's pretty annoying that backpack clears my console when I run backpack build, there's really no reason to go immersive there 😊

CLI options (--entry)

Hey! I really love how easy backpack makes writing scripts and servers :D

One thing that I would like to see is the ability to provide some options when running backpack. I know it is mainly build to run "a project" now, but when writing scripts I sometimes want to run specific files to test them out or bootstrap something quickly.

I suggest adding a --entry <file> option, that would... use a different entry file :D

If this is something you think would be cool (😎) I'd love to make a PR for it!

Global CLI, init command

  • Make a globally installable CLI Like CRA's that never needs to be upgraded as it is just a wrapper around the latest version of backpack-core.
  • Add backpack init command with template

RFC: Support for warn-require

Would be nice if this project could feature something like HMR but for backend. warm-require is a module that makes this possible. Thoughts?

Wrong absolute path of source-map-support at build time

Seems to be an escape problem at the time of parsing. (backpack-core version 0.0.9)

The backslashs from requrie.resolve is scaped on build time and escaped again at runtime.
I use Windows and the implementation of source-map-support in version 0.0.8 works well

Expected: C:\\Users\\Name\\Dir\\Project\\node_modules\\source-map-support\\source-map-support.js

Currently built and fails:
Image

Error log:

DONE Compiled successfully in 321ms

module.js:471
throw err;
^

Error: Cannot find module 'C:UsersNameDirProject
ode_modulessource-map-supportsource-map-support.js'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (C:\Users\Name\Dir\Project\build\main.js:1:63)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Migrate to Webpack 3.x

Webpack 3 was released, and they want to publish new versions more often. A pull request exists #60

Is it wanted to follow the release process of Webpack? What are the criteria to choose when to upgrade and to which Webpack version?

add node debug support

would be nice to be able to attach to node process and specify debug port (maybe nodeDebug (number) option in package.json, if present in dev mode node is run with specified debug port or default one 5858)

can be implemented passing --debug={portNumber} to nodemon

...
nodemon({ script: mainPath, watch: serverPaths, flags: [], nodeArgs: [`--debug=${portNumber}`] })
...

How to pass args/params when running backpack ?

Hello I would like to run my backpack application with a specific arg..

something like this:

./node_modules/.bin/backpack hello
or
yarn dev hello

the goal is to check the argument like this:
const param = process.argv[2]

and work with that variable.

Is there a way to do that with backpack ?

kind regards,
Joao.

[IDEA] Allow for Universal Apps with HMR

Currently Backpack is focused on providing the best development experience for Node.js server-side applications and libraries.

This was a deliberate decision.

The idea is that people should use tools like Create React App or Next.js for their frontend and then use Backpack to build out API's etc. My goal was to create a complimentary tool.

However, it appears that the community wants a some sort of drop-in solution like CRA's react-scripts but for isomorphic / universal apps. I'm not sure why it isn't more popular, but this is what the New York Times' kyt project aims to do. Personally, I don't care for the aesthetics of kyt (e.g. the emoji's in the console) and for some of the conventions (like extract text/css and the eslint-config airbnb), but those are just my opinions. Regardless, Backpack could technically accommodate universal apps with a few small, yet non-trivial modifications.

In my research, I've come up with two approaches to Universal Apps with Hot Module Replacement and server reloading worth considering:

(Note: these have been extracted from other React server-side rendered projects of mine. However, they are not yet drop-in replacements to backpack dev. They do not currently handle custom webpack modifications like Backpack's currently does. These are just POC's).

1. Chokidar, Nodemon, Webpack-Hot-Middleware

This serves up client-side assets on another port like localhost:3001. It would be up to the user to properly reference where the assets are served from in their apps. This isn't necessarily a bad thing though, as these frontend assets should ideally be served from a CDN in production anyways. We could handle this by providing a Webpack flag to the server for use in the application's HTML template such as BACKPACK_ASSETS_URL.

// Proof of concept #1 dev.js
const nodemon = require('nodemon')
const path = require('path')
const chokidar = require('chokidar')
const express = require('express')
const webpack = require('webpack')
const url = require('url')
const once = require('ramda').once
const devMiddleware = require('webpack-dev-middleware')
const hotMiddleware = require('webpack-hot-middleware')
const serverConfig = require('../config/webpack.dev.server')
const clientConfig = require('../config/webpack.dev.client')
const { clientUrl, serverSrcPath } = require('../config/paths')

process.on('SIGINT', process.exit)
let clientCompiler, serverCompiler

const startServer = () => {
  const serverPaths = Object
    .keys(serverCompiler.options.entry)
    .map(entry => path.join(serverCompiler.options.output.path, `${entry}.js`))
  const mainPath = path.join(serverCompiler.options.output.path, 'main.js')
  nodemon({ script: mainPath, watch: serverPaths, flags: [] })
    .once('start', () => {
      //console.log(`NODEMON: Server running at: ${'http://localhost:3000'}`)
      //console.log('NODEMON: Development started')
    })
    // .on('restart', () => console.log('Server restarted'))
    .on('quit', process.exit)
}

const afterClientCompile = once(() => {
  // console.log('[WEBPACK-CLIENT]: Setup RHL')
  // console.log('[WEBPACK-CLIENT]: Done compiling client')
})

const compileServer = () => serverCompiler.run(() => undefined)

clientCompiler = webpack(clientConfig, (err, stats) => {
  if (err) return
  afterClientCompile()
  compileServer()
})

const startClient = () => {
  const devOptions = clientCompiler.options.devServer
  const app = express()
  const webpackDevMiddleware = devMiddleware(clientCompiler, devOptions)
  app.use(webpackDevMiddleware)
  app.use(hotMiddleware(clientCompiler, {
    log: () => {}
  }))
  app.listen(url.parse(clientUrl).port)
  // console.log('[WEBPACK-CLIENT]: Started asset server on http://localhost:' + url.parse(clientUrl).port)
}

const startServerOnce = once(() => startServer())

const watcher = chokidar.watch([serverSrcPath])

watcher.on('ready', () => {
  watcher
    .on('add', compileServer)
    .on('addDir', compileServer)
    .on('change', compileServer)
    .on('unlink', compileServer)
    .on('unlinkDir', compileServer)
})

serverCompiler = webpack(serverConfig, (err, stats) => {
  if (err) return
  startServerOnce()
})

startClient()

2. BrowserSync, Proxy-Middleware, Webpack-Hot-Middleware

The following is heavily inspired by Ueno's React Starter project.. It uses a http-proxy and browser-sync to work out the ports. My only criticism of this technique is that browser-sync and Docker do not play nicely with each other at all (last time i checked). That is either irrelevant or a dealbreaker for people.

const path = require('path')
const url = require('url')
const bs = require('browser-sync').create();
const webpack = require('webpack')
const proxyMiddleware = require('http-proxy-middleware');
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const color = require('cli-color');
const debug = require('./debug');
const serverConfig = require('./webpack.dev.server')
const clientConfig = require('./webpack.dev.client')
const { clientUrl, serverSrcPath } = require('./buildConfig')

const domain = color.magentaBright('webpack');

// Get ports
const port = (parseInt(process.env.PORT, 10) || 3000) - 1;
const proxyPort = port + 1;

// Create compilers
const clientCompiler = webpack(clientConfig);
const serverCompiler = webpack(serverConfig);

// Logging
const log = (...args) => debug(domain, ...args);

// Build container
const build = {
  failed: false,
  first: true,
  connections: [],
};

const devMiddleware = webpackDevMiddleware(clientCompiler, {
  publicPath: '/',
  noInfo: true,
  quiet: true,
  stats: {
    timings: false,
    version: false,
    hash: false,
    assets: false,
    chunks: false,
    colors: true,
  },
});

serverCompiler.plugin('done', stats => {

  if (stats.hasErrors()) {
    log(color.red.bold('build failed'));
    build.failed = true;
    return;
  }

  if (build.failed) {
    build.failed = false;
    log(color.green('build fixed'));
  }

  log('built %s in %sms', stats.hash, stats.endTime - stats.startTime);

  const opts = serverCompiler.options;
  const outputPath = path.resolve(opts.output.path, `${Object.keys(opts.entry)[0]}.js`);
  // Make sure our newly built server bundles aren't in the module cache.
  Object.keys(require.cache).forEach((modulePath) => {
    if (modulePath.indexOf(opts.output.path || outputPath) !== -1) {
      delete require.cache[modulePath];
    }
  });

  if (build.listener) {
    // Close the last server listener
    build.listener.close();
  }

  // Start the server
  build.listener = require(outputPath).default; // eslint-disable-line

  // Track all connections to our server so that we can close them when needed.
  build.listener.on('connection', (connection) => {
    // Fixes first request to the server when nothing has been hot reloaded
    if (build.first) {
      devMiddleware.invalidate();
      build.first = false;
    }

    build.connections.push(connection);
    connection.on('close', () => {
      build.connections.splice(build.connections.indexOf(connection));
    });
  });
});

log(`started on ${color.blue.underline(`http://localhost:${proxyPort}`)}`);

serverCompiler.watch({
  aggregateTimeout: 300,
  poll: true,
}, () => undefined);

clientCompiler.watch({
  aggregateTimeout: 300,
  poll: true,
}, () => undefined);

// Initialize BrowserSync
bs.init({
  port: proxyPort,
  open: false,
  notify: false,
  logLevel: 'silent',
  server: {
    baseDir: './',
    middleware: [
      devMiddleware,
      webpackHotMiddleware(clientCompiler, {
        log: () => {}
      }),
      proxyMiddleware(p => !p.match('^/browser-sync'), {
        target: `http://localhost:${port}`,
        changeOrigin: true,
        ws: true,
        logLevel: 'warn',
      }),
    ],
  },
});

process.on('SIGTERM', () => {
  if (build.listener) {
    build.listener.close(() => {
      log('closing %s connections', build.connections.length);
      log('shutting down');
      build.connections.forEach(conn => {
        conn.destroy();
      });
      process.exit(0);
    });
  }
});

Anyways, those are some ideas. I'd love to get the discussion going. I've been thinking about this since reading @jlongster 's Backend Apps with Webpack

Using backpack with blessed - preventing echoing input

When running backpack as in npm run dev, input to the terminal is echoed back (type 'c' in your terminal and you immediately see 'c' in the terminal, like you'd generally expect).

However, blessed projects are expected to handle all screen actions themselves. When using backpack with a blessed project and running backpack, this input echoing messes up blessed's screen printing.

Example showing input echoed from moving mouse over terminal:

image

This issue does not occur when running code built by backpack build, so I'm confident this could be remedied by disabling input echoing when running backpack. Is there a CLI flag to do this, or could you suggest how I might go about implementing this in either my script or as a PR for backpack?

Built project, dependency error

I installed backpack via yarn add backpack-core --dev as the docs stated, and added build scripts as described to package.json.

I then built my program via yarn run build, removed my node_modules folder, and reinstalled with yarn --production.

I then ran node build/main, and this immediately failed because I was missing the module use-source-maps, which Webpack had required at the start of the built script.

Of course, with backpack-core installed, this is not an issue.
Could we please either amend the docs to say to install backpack-core as a full on dependency, or (preferred) direct Webpack to not generate sourcemaps when running backpack build?

My opinion on that is, when I'm running backpack in a dev environment, I want source maps to be there. However when I'm running in production, I no longer care about source maps, so I'd rather not have the (comparatively massive) dependencies of Babel and Webpack hanging around for something I don't care about. I assume this is your opinion too, since you want backpack to be installed via --save-dev.

Of course I know that I can manually configure these options (and plan to do so if necessary), but I love the concept of this package being easy to use and having sensible defaults.

Thanks for your time!

Good Work :D

We need stuff like this in the JS build ecosystem so keep up the good work :D
I'm building systemjs-tools which is in a similar space but for the SystemJS ecosystem.

Mobx support?

Decorators are not officially supported yet in 6.x pending a proposal update.
However, if you need to use them you can install the legacy decorators transform with:

npm install babel-plugin-transform-decorators-legacy --save-dev

and add the following line to your .babelrc file:

{
  "plugins": ["transform-decorators-legacy"]
}

The repo url is: https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy.
    

  4 | 
  5 | @observer
> 6 | class Mobx extends React.Component {
    | ^
  7 |   componentDidMount () {
  8 | 
  9 |   }

I have followed that and still get the same error.

My babelrc looks like

{
"presets": [
"backpack-core/babel",
"stage-0"
],
"plugins": ["transform-decorators-legacy"]
}

How to use backpack to compile the main electron process?

Hi,

In the backpack.config.js, I am setting the target to be electron-main but when I run backpack, backpack fails to find the electron package. What's the best way to use backpack to compile just the main process with backpack?

Thanks

Custom entry point

Are there any ways to define custom entry points other than src/index.js?

Critical dependency: the request of a dependency is an expression

Hi,
I'm trying to use socket.io with my express server and I get this warnings:

warning  in ./node_modules/socket.io/lib/index.js
108:11-32 Critical dependency: the request of a dependency is an expression

warning  in ./node_modules/engine.io/lib/server.js
115:15-37 Critical dependency: the request of a dependency is an expression

warning  in ./node_modules/bindings/bindings.js
76:22-40 Critical dependency: the request of a dependency is an expression

warning  in ./node_modules/bindings/bindings.js
76:43-53 Critical dependency: the request of a dependency is an expression

In my package.json :

"dependencies": {
    "babel-preset-stage-3": "^6.22.0",
    "backpack-core": "^0.4.0-rc1",
    "bufferutil": "^3.0.2",
    "express": "^4.15.3",
    "socket.io": "^2.0.3",
    "utf-8-validate": "^3.0.3",
    ...
},
"scripts": {
    "build": "NODE_ENV=production backpack build",
    "start": "NODE_ENV=development backpack",
    ....
},

and my express config :

import express from 'express'
import SocketIO from 'socket.io'
import { Server } from 'http'

const app = express()
const io = SocketIO(Server(app))
const { PORT } = process.env

app.listen(PORT, () => log(`[Express] Api is running on port ${PORT}`))

io.on('connection', socket => {
  socket.emit('news', { hello: 'world' })
  socket.on('my other event', data => {
    log(data)
  })
})

It work fine without socket.io

[Critical] Error when adding backpack, in aligned-buffer dependency

Command used:

npm install --save-dev backpack

or

yarn add -D backpack

Output:

npm install --save-dev backpack

> [email protected] install /Users/ilyes/my-boilerplate/node_modules/aligned-buffer
> node-gyp rebuild

  CXX(target) Release/obj.target/aligned_buffer/src/aligned-buffer.o
../src/aligned-buffer.cc:16:52: error: no member named 'New' in 'v8::String'
    return ThrowException(Exception::Error(String::New(what)));
                                           ~~~~~~~~^
../src/aligned-buffer.cc:19:31: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
Handle<Value> alignment(const Arguments &args) {
                              ^~~~~~~~~
                              v8::internal::Arguments
/Users/ilyes/.node-gyp/6.4.0/include/node/v8.h:145:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../src/aligned-buffer.cc:20:45: error: too few arguments to function call, expected 2, have 1
    return Number::New(sysconf(_SC_PAGESIZE));
           ~~~~~~~~~~~                      ^
/Users/ilyes/.node-gyp/6.4.0/include/node/v8.h:2534:3: note: 'New' declared here
  static Local<Number> New(Isolate* isolate, double value);
  ^
../src/aligned-buffer.cc:23:28: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
Handle<Value> buffer(const Arguments &args) {
                           ^~~~~~~~~
                           v8::internal::Arguments
/Users/ilyes/.node-gyp/6.4.0/include/node/v8.h:145:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../src/aligned-buffer.cc:24:13: error: member access into incomplete type 'const v8::internal::Arguments'
    if (args.Length() < 2) {
            ^
/Users/ilyes/.node-gyp/6.4.0/include/node/v8.h:145:7: note: forward declaration of 'v8::internal::Arguments'
class Arguments;
      ^
../src/aligned-buffer.cc:28:37: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    size_t alignment = (size_t) args[0]->ToNumber()->Value();
                                ~~~~^~
../src/aligned-buffer.cc:29:37: error: type 'const v8::internal::Arguments' does not provide a subscript operator
    size_t size      = (size_t) args[1]->ToNumber()->Value();
                                ~~~~^~
../src/aligned-buffer.cc:42:5: error: unexpected namespace name 'Buffer': expected expression
    Buffer * Result = Buffer::New((char *) buf, size, free_aligned_buffer, NULL);
    ^
../src/aligned-buffer.cc:42:14: error: use of undeclared identifier 'Result'; did you mean 'result'?
    Buffer * Result = Buffer::New((char *) buf, size, free_aligned_buffer, NULL);
             ^~~~~~
             result
../src/aligned-buffer.cc:32:9: note: 'result' declared here
    int result = posix_memalign(&buf, alignment, size);
        ^
../src/aligned-buffer.cc:42:23: error: no matching function for call to 'New'
    Buffer * Result = Buffer::New((char *) buf, size, free_aligned_buffer, NULL);
                      ^~~~~~~~~~~
/Users/ilyes/.node-gyp/6.4.0/include/node/node_buffer.h:34:40: note: candidate function not viable: requires at most 3
      arguments, but 4 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/ilyes/.node-gyp/6.4.0/include/node/node_buffer.h:46:40: note: candidate function not viable: requires 3
      arguments, but 4 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/ilyes/.node-gyp/6.4.0/include/node/node_buffer.h:39:40: note: candidate function not viable: requires 5
      arguments, but 4 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/ilyes/.node-gyp/6.4.0/include/node/node_buffer.h:31:40: note: candidate function not viable: requires 2
      arguments, but 4 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, size_t length);
                                       ^
../src/aligned-buffer.cc:44:17: error: calling a protected constructor of class 'v8::HandleScope'
    HandleScope scope;
                ^
/Users/ilyes/.node-gyp/6.4.0/include/node/v8.h:904:13: note: declared protected here
  V8_INLINE HandleScope() {}
            ^
../src/aligned-buffer.cc:46:18: error: no member named 'Close' in 'v8::HandleScope'
    return scope.Close(Result->handle_);
           ~~~~~ ^
../src/aligned-buffer.cc:46:24: error: use of undeclared identifier 'Result'
    return scope.Close(Result->handle_);
                       ^
../src/aligned-buffer.cc:51:5: error: no matching function for call to 'NODE_SET_METHOD'
    NODE_SET_METHOD(target, "alignment", alignment);
    ^~~~~~~~~~~~~~~
/Users/ilyes/.node-gyp/6.4.0/include/node/node.h:269:25: note: expanded from macro 'NODE_SET_METHOD'
#define NODE_SET_METHOD node::NODE_SET_METHOD
                        ^~~~~~~~~~~~~~~~~~~~~
/Users/ilyes/.node-gyp/6.4.0/include/node/node.h:257:13: note: candidate function not viable: no known conversion from
      'Handle<v8::Value> (const v8::internal::Arguments &)' (aka 'v8::Local<v8::Value>
      (const v8::internal::Arguments &)') to 'v8::FunctionCallback' (aka 'void (*)(const
      FunctionCallbackInfo<v8::Value> &)') for 3rd argument
inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
            ^
/Users/ilyes/.node-gyp/6.4.0/include/node/node.h:244:13: note: candidate function not viable: no known conversion from
      'Handle<v8::Value> (const v8::internal::Arguments &)' (aka 'v8::Local<v8::Value>
      (const v8::internal::Arguments &)') to 'v8::FunctionCallback' (aka 'void (*)(const
      FunctionCallbackInfo<v8::Value> &)') for 3rd argument
inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
            ^
../src/aligned-buffer.cc:52:5: error: no matching function for call to 'NODE_SET_METHOD'
    NODE_SET_METHOD(target, "buffer", buffer);
    ^~~~~~~~~~~~~~~
/Users/ilyes/.node-gyp/6.4.0/include/node/node.h:269:25: note: expanded from macro 'NODE_SET_METHOD'
#define NODE_SET_METHOD node::NODE_SET_METHOD
                        ^~~~~~~~~~~~~~~~~~~~~
/Users/ilyes/.node-gyp/6.4.0/include/node/node.h:257:13: note: candidate function not viable: no known conversion from
      'Handle<v8::Value> (const v8::internal::Arguments &)' (aka 'v8::Local<v8::Value>
      (const v8::internal::Arguments &)') to 'v8::FunctionCallback' (aka 'void (*)(const
      FunctionCallbackInfo<v8::Value> &)') for 3rd argument
inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
            ^
/Users/ilyes/.node-gyp/6.4.0/include/node/node.h:244:13: note: candidate function not viable: no known conversion from
      'Handle<v8::Value> (const v8::internal::Arguments &)' (aka 'v8::Local<v8::Value>
      (const v8::internal::Arguments &)') to 'v8::FunctionCallback' (aka 'void (*)(const
      FunctionCallbackInfo<v8::Value> &)') for 3rd argument
inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
            ^
15 errors generated.
make: *** [Release/obj.target/aligned_buffer/src/aligned-buffer.o] Error 1

Running command as sudo does not correct error.
System info :

  • Macbook Pro 13" 2016
  • OS El Capitan 10.11.5

I want to use others NODE_ENV

In the use of backpack process, only two kinds of NODE_ENV, production & development, how can i definied NODE_ENV by myself, like beta, test ...

Integrate HappyPack to speed up builds

HappyPack significantly reduces webpack build times by using parallel execution.

I was able to make it work with babel-loader by adding the following to my backpack.config.js:

const HappyPack = require('happypack');

module.exports = {
  webpack: config => {
    let babelOptions;
    config.module.rules = config.module.rules.map(rule => {
      if (rule.loader === 'babel-loader') {
        babelOptions = rule.options;

        return {
          test: rule.test,
          exclude: rule.exclude,
          use: {
            loader: require.resolve('happypack/loader'),
            query: {id: 'babel'},
          },
        };
      }

      return rule;
    });
    config.plugins = [
      ...config.plugins,
      new HappyPack({
        id: 'babel',
        loaders: [
          {
            path: require.resolve('babel-loader'),
            query: babelOptions,
          },
        ],
        verbose: false,
      }),
    ];

    return config;
  },
};

However, it would be great to have this set up by default.

Willing to make a PR if this is something you would want to add.

Error: Cannot find module

module.js:442
    throw err;
    ^

Error: Cannot find module 'F:\Main Projectes\NUXT\"F:\Main '
    at Function.Module._resolveFilename (module.js:440:15)
    at Function.Module._load (module.js:388:25)
    at Module.runMain (module.js:575:10)
    at run (bootstrap_node.js:352:7)
    at startup (bootstrap_node.js:144:9)
    at bootstrap_node.js:467:3

this weird bugging for days .i started a project with nuxt and i cloned fresh nuxt template and i tried to run dev server and getting this error.

i tried build and it woks fine . but only dev server not working
i am running on windows 10 and reinstalled my OS and this error! its still there

i am running on windows 10
NODE v6.3.1
NPM 5.0.3

Cannot find module Source-map-support

Hi, I'm trying to push my build on production and I'm getting this error

Cannot find module '/Users/NAME/FOLDER/PROJECT_NAME/node_modules/source-map-support/source-map-support.js'

Anyone know how to fix this?

Thank you very much!

Feature request: REPL

I usually add a REPL to my apps in development mode with some context variables like express, the database ORM and some other variables like this:

import express from 'express';
import mongoose from 'mongoose';
import repl from 'repl';

const app = express();
// ...

if (process.env.NODE_ENV === 'development') {
  const instance = repl.start({
    prompt: 'app > ',
  });
  instance.context.app = app;
  instance.context.mongoose = mongoose;
}

A huge feature would be adding a REPL to npm run dev with backpack. Even better with async/await support.

$ backpack
 DONE  Compiled successfully in 1645ms

 > const songs = await mongoose.model('Song').find();
 [ ... ]

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.