function runDevServer() {
  var app;

  const compiler = Object.create(webpack(configsList), { outputPath: { value: PUBLIC_DIR }});
  const server = new WebpackDevServer(compiler, DEV_OPTIONS);

  compiler.plugin('done', function onCompilationDone() {
    app = recompileApp(server.middleware.fileSystem.readFileSync(SERVER_FILENAME, 'utf8'));
  });

  server.use('/', function proxyApp(req, res, next) {
    const send_ = res.send;

    res.send = function send(content) {
      if (res.statusCode >= 400) {
        const tag = ['body', 'head', 'html'].find(function(tag) { return !!~content.indexOf('</' + tag + '>') });

        if (tag) {
          content = content.replace('</' + tag + '>', DEV_INDEX_SCRIPT + '$&');
        } else {
          content += DEV_INDEX_SCRIPT;
        }
      }

      return send_.call(this, content);
    };

    return app(req, res, next);
  });

  server.listen(PORT, HOST);
}
function startAppServer(callback) {
    // Serve the Relay app
    const compiler = webpack({
        entry: path.resolve(__dirname, 'js', 'app.js'),
        module: {
            loaders: [
                {
                    exclude: /node_modules/,
                    loader: 'babel',
                    test: /\.js$/,
                }
            ]
        },
        output: {filename: '/app.js', path: '/', publicPath: '/js/'}
    });
    appServer = new WebpackDevServer(compiler, {
        contentBase: '/public/',
        proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
        publicPath: '/js/',
        stats: {colors: true}
    });
    // Serve static resources
    appServer.use('/', express.static(path.resolve(__dirname, 'public')));
    appServer.listen(APP_PORT, () => {
        console.log(`App is now running on http://localhost:${APP_PORT}`);
        if (callback) {
            callback();
        }
    });
}
Beispiel #3
0
export const createDevServer = (config) => {
  const webpackConfig = config.webpackConfig
  const compiler = createDevCompiler(
    webpackConfig,
    `webpack-dev-server/client?http://localhost:${config.port}`
  )

  const server = new WebpackDevServer(compiler, {
    // webpack-dev-middleware options.
    publicPath: webpackConfig.output.publicPath,
    quiet: false,
    noInfo: false,
    stats: {
      // https://webpack.github.io/docs/node.js-api.html#stats-tojson
      assets: true,
      colors: true,
      version: true,
      hash: true,
      timings: true,
      chunks: false
    },

    // webpack-dev-server options.
    contentBase: false,
    setup(app) {
      // This runs before webpack-dev-middleware.
      app.disable('x-powered-by')
      app.use(morgan('dev'))
    }
  })

  // This runs after webpack-dev-middleware.
  server.use(devErrorHandler())
  server.use(express.static(config.publicDir))
  server.use(devAssets(compiler))
  server.use(createRouter(config))

  return server
}
Beispiel #4
0
gulp.task("webpack-dev-server", function() {
    // modify some webpack config options
    var myConfig = Object.create(webpackConfig);
    myConfig.devtool = "eval";
    myConfig.debug = true;

    // Start a webpack-dev-server
    var server = new WebpackDevServer(webpack(myConfig), {
        contentBase: __dirname,
        hot: true,
        quiet: false,
        noInfo: false,
        publicPath: "/build/",
        stats: { colors: true }
    });
    
    server.use('/api', proxy('http://ec2-52-27-255-166.us-west-2.compute.amazonaws.com:9000', {
      forwardPath: function(req, res) {
        return require('url').parse(req.url).path;
      }
    }));

    server.use(function(req, res, next) {
        if (req.headers && req.headers['x-requested-with'] === 'XMLHttpRequest') {
          return next();
        }
        res.statusCode = 200;
        res.write(fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf8'));
        res.end();
    });
    
    server.listen(8090, "localhost", function(err) {
        if(err) throw new gutil.PluginError("webpack-dev-server", err);
        gutil.log("[webpack-dev-server]", "http://localhost:8050/webpack-dev-server/index.html");
    }); 
});
gulp.task('webpack-dev-server', function() {
  var app = new WebpackDevServer(compiler, {
    publicPath: '/static/',
    hot: true,
    historyApiFallback: true,
    stats: {
      colors: true,
      assets: false,
      chunks: false
    }
  });
  // Serve static resources
  app.use('/', express.static(path.resolve(__dirname, 'public')));
  app.listen(APP_PORT, () => {
    console.log(`App is now running on http://localhost:${APP_PORT}`);
  });
});
Beispiel #6
0
function startRelayServer() {
  // Launch Relay by using webpack.config.js
  relayServer = new WebpackDevServer(webpack(webpackConfig), {
    contentBase: '/build/',
    proxy: {
      '/graphql': `http://localhost:${config.graphql.port}`
    },
    stats: {
      colors: true
    },
    hot: true,
    historyApiFallback: true
  });

  // Serve static resources
  relayServer.use('/', express.static(path.join(__dirname, '../build')));
  relayServer.listen(config.port, () => console.log(`Relay is listening on port ${config.port}`));
}
  return copyConfigFiles().then(() => {
    const compiler = webpack(require('../webpack.config.js')) // eslint-disable-line

    const devServer = new WebpackDevServer(compiler, compiler.options.devServer)

    devServer.use(devServer.middleware)

    // Launch WebpackDevServer
    return new Promise((resolve, reject) => {
      devServer.listen(port, (err, result) => {
        if (err) {
          reject(err)
          return
        }
        // resolve(); if we resolve the server closes
      })
    })
  })
Beispiel #8
0
function startAppServer(callback) {
  // Serve the Relay app
  var compiler = webpack(config);

  appServer = new WebpackDevServer(compiler, {
    contentBase: '/src/',
    proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
    publicPath: '/dist/',
    stats: {colors: true}
  });
  // Serve static resources
  appServer.use('/', express.static(path.resolve(__dirname, 'dist')));
  appServer.listen(APP_PORT, () => {
    console.log(`App is now running on http://localhost:${APP_PORT}`);
    if (callback) {
      callback();
    }
  });
}
Beispiel #9
0
export function getServer(inPath: string, {react, port, contentBase, configureApplication}: DevServerConfig) {
  const server = new WebpackDevServer(webpack({
    ...getConfig(react),
    devtool: 'eval-source-map',
    entry: [
      `webpack-dev-server/client?http://0.0.0.0:${port}`,
      'webpack/hot/only-dev-server',
      'babel-polyfill',
      inPath
    ],
    output: {path: contentBase, filename: 'script.js', publicPath: '/'},
    plugins: serverPlugins
  }), {contentBase: false, publicPath: '/', hot: true});

  server.use(serveStatic(contentBase));
  configureApplication(server.app);

  return server;
}
Beispiel #10
0
gulp.task('webpack-dev-server', function(cb) {
  if (webpackCalled) {
    console.log('webpack dev server already runnning');
    return cb();
  }
  var devServerOptions = {
    headers: {
      'Access-Control-Allow-Credentials': 'true'
    },
    hot: true,
    noInfo: true,
    contentBase: false,
    publicPath: '/js'
  };
  webpackConfig.entry.bundle = [
    'webpack-dev-server/client?http://localhost:2999/',
    'webpack/hot/dev-server'
  ].concat(webpackConfig.entry.bundle);

  var compiler = webpack(webpackConfig);
  var devServer = new WebpackDevServer(compiler, devServerOptions);
  devServer.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
    next();
  });
  return devServer.listen('2999', 'localhost', function(err) {
      if (err) {
        throw new gutil.PluginError('webpack-dev-server', err);
      }

      if (!webpackCalled) {
        gutil.log('[webpack-dev-server]', 'webpack init completed');
        webpackCalled = true;
        cb();
      }

    });
});
Beispiel #11
0
function uerProxy(target,host){
    app.use(target, proxy(host, {
        /* filter: function(req, res) {
         return req.method == req.method;
         },*/
        forwardPath: function(reqOpt, res) {
            if(target!='/hoststro'&&target!='/fileService'){
                reqOpt.headers['Content-Type'] = 'application/json';
            }
            delete reqOpt.headers.host;
            //console.log('res:',res);
            //logger.debug("reqUrl=%s",host+reqOpt.url);
            console.log('reqUrl:',host+reqOpt.url);
            return require('url').parse(reqOpt.url).path;
        }
        ,intercept: function(rsp, data, req, res, callback) {
            // rsp - original response from the target
            if(rsp.headers['Content-Type'] == 'application/json'){
                console.log(data);
                data = JSON.parse(data.toString('utf8'));
                callback(null, JSON.stringify(data));
            }else{
                callback(null, data);
            }
        }
        /* ,decorateRequest: function(reqOpt, req) {
         /!*  reqOpt.headers['Content-Type'] = '';
         reqOpt.method = 'GET';*!/
         // reqOpt.bodyContent = wrap(req.bodyContent);
         return reqOpt;
         }*/
        ,reqBodyEncoding: null
        ,preserveHostHdr: true
        ,limit:'5mb'
    }));
}
  stats: { colors: true },
};

if (config.proxy) {
  serverOptions.proxy = {
    '*': {
      target: config.proxy,
      changeOrigin: true,
      bypass: (req, res, proxyOptions) => {
        if (req.url.includes('__webpack_hmr')) {
          return req.url;
        }
      },
    },
  };
}

const server = new WebpackDevServer(compiler, serverOptions);

server.use(hotMiddleware);
spinner.stop();

server.listen(config.port, err => {
  if (err) {
    console.log(err);
    return;
  }

  console.log('====> http://localhost:' + config.port + '\n');
});
Beispiel #13
0
import WebpackDevServer from 'webpack-dev-server';
import express from 'express';
import path from 'path';

var compiler = webpack({
	entry: path.join(__dirname, 'src', 'app.js'),
	module: {
		loaders: [
			{
				test: /\.js$/,
				loader: 'babel'
			}
		]
	},
	output: {
		filename: 'app.js',
		publicPath: path.join(__dirname, 'dist'),
		path: '/dist/'
	}
});

var app = new WebpackDevServer(compiler, {
	contentBase: '/dist/',
	stats: {coloes: true}
});

app.use('/api', require('./apis'));
app.use('/', express.static('dist'));
app.listen(80, () => {
	console.log(`Webpack dev server now running at port: 80`);
});
Beispiel #14
0
var compiler = webpack(config)
var app = new WebpackDevServer(compiler, {
  // publicPath: config.output.publicPath,
  historyApiFallback: true,
  proxy: proxy,
  hot: true,
  stats: {
    colors: true,
    chunks: false
  }
});

var hotMiddleware = require('webpack-hot-middleware')(compiler)
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
   	hotMiddleware.publish({ action: 'reload' })
    cb()
  })
})

app.use(hotMiddleware)

app.listen(3001, '0.0.0.0', function (err, result) {
  console.log('http://localhost:3001');
  if (err) {
    console.log(err);
  }
});
Beispiel #15
0
module.exports = function(args, subprocess) {
  const cwd = process.cwd();
  const HOST = args.host || '0.0.0.0';
  const PORT = args.port || 3333;

  const send = function(data) {
    iceworksClient.send(data);
    if (subprocess && typeof subprocess.send === 'function') {
      subprocess.send(data);
    }
  };

  const LOCAL_IP = address.ip();

  const isInteractive = false; // process.stdout.isTTY;
  const entries = getEntries(cwd, false);
  const paths = getPaths(cwd);

  const packageData = require(paths.appPackageJson);
  // get ice config by package.ice

  const webpackConfig = getWebpackConfigDev(
    entries,
    paths,
    packageData.buildConfig || packageData.ice
  );

  if (iceworksClient.available) {
    webpackConfig.plugins.push(
      new webpack.ProgressPlugin((percentage, msg) => {
        send({
          type: 'sdk_status',
          message: 'dev_compiler_progress',
          data: { percentage, msg },
        });
      })
    );
  }

  let isFirstCompile = true;
  const compiler = webpack(webpackConfig);
  const devServerConfig = require('./config/webpack.server.config')(
    paths,
    args
  );
  const devServer = new WebpackDevServer(compiler, devServerConfig);

  compiler.plugin('done', (stats) => {
    if (isInteractive) {
      clearConsole();
    }
    if (isFirstCompile) {
      send({
        type: 'sdk_status',
        message: 'dev_server_finished',
        data: {
          url: `http://${LOCAL_IP}:${PORT}`,
        },
      });

      isFirstCompile = false;
      console.log(chalk.cyan('Starting the development server...'));
      console.log('   ', chalk.yellow(`http://localhost:${PORT}`));
      console.log('   ', chalk.yellow(`http://${LOCAL_IP}:${PORT}`));
    }

    console.log(
      stats.toString({
        colors: true,
        chunks: false,
        assets: true,
        children: false,
        modules: false,
      })
    );

    const json = stats.toJson({}, true);
    const messages = formatWebpackMessages(json);
    const isSuccessful = !messages.errors.length && !messages.warnings.length;

    if (isSuccessful) {
      if (stats.stats) {
        console.log(chalk.green('Compiled successfully'));
      } else {
        console.log(
          chalk.green(
            `Compiled successfully in ${(json.time / 1000).toFixed(1)}s!`
          )
        );
      }
    }

    if (messages.errors.length) {
      if (messages.errors.length > 1) {
        messages.errors.length = 1;
      }
      console.log(chalk.red('Failed to compile.\n'));
      console.log(messages.errors.join('\n\n'));
    } else if (messages.warnings.length) {
      console.log(chalk.yellow('Compiled with warnings.'));
      console.log();
      messages.warnings.forEach((message) => {
        console.log(message);
        console.log();
      });
      // Teach some ESLint tricks.
      console.log('You may use special comments to disable some warnings.');
      console.log(
        `Use ${chalk.yellow(
          '// eslint-disable-next-line'
        )} to ignore the next line.`
      );
      console.log(
        `Use ${chalk.yellow(
          '/* eslint-disable */'
        )} to ignore all warnings in a file.`
      );
      console.log();
    }

    if (isSuccessful) {
      // 服务启动完成切没有任务错误与警告
      send({
        type: 'sdk_status',
        message: 'dev_compiler_success',
        data: {
          url: `http://${LOCAL_IP}:${PORT}`,
        },
      });
    } else {
      // 服务启动完成切没有任务错误与警告
      send({
        type: 'sdk_status',
        message: 'dev_compiler_failed',
        data: {
          url: `http://${LOCAL_IP}:${PORT}`,
        },
      });
    }
  });

  compiler.plugin('invalid', () => {
    if (isInteractive) {
      clearConsole();
    }
    console.log('Compiling...');
    send({
      type: 'sdk_status',
      message: 'dev_compiler_compiling',
    });
  });

  devServer.use(function(req, res, next) {
    console.log('Time:', Date.now());
    next();
  });

  devServer.listen(PORT, HOST, (err) => {
    if (err) {
      send({
        type: 'sdk_status',
        message: 'dev_server_failed',
      });
      return console.log(err);
    } else {
      send({
        type: 'sdk_status',
        message: 'dev_server_success',
        data: {
          url: `http://${LOCAL_IP}:${PORT}`,
        },
      });
    }
  });
};
Beispiel #16
0
var path = require('path');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config.js');

config.entry.push(
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server'
);

config.plugins.push(new webpack.HotModuleReplacementPlugin());

var server = new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    contentBase: '../static/',
    historyApiFallback: true
});

server.use('/', function (request, response) {
    response.sendFile(path.resolve(__dirname, '../', 'static', 'react_index.html'));
});

server.listen(3000, 'localhost', function (err, result) {
    if (err) {
        return console.log(err);
    }
    console.log('Listening at http://localhost:3000/');
});
const compiler = webpack(webpackConfig);
const app = new WebpackDevServer(compiler, {
    hot: true,
    proxy: {
        "/graphql": `http://localhost:${GRAPHQL_PORT}`
    },
    // It suppress error shown in console, so it has to be set to false.
    quiet: false,
    // It suppress everything except error, so it has to be set to false as well
    // to see success build.
    noInfo: false,
    stats: {
        // Config for minimal console.log mess.
        assets: false,
        colors: true,
        version: false,
        hash: false,
        timings: false,
        chunks: false,
        chunkModules: false
    }
});

// Serve static resources
app.use("/", express.static(path.resolve(__dirname, "dist")));
app.listen(APP_PORT, () => {
    console.log(`App is now running on http://localhost:${APP_PORT}`);
});

/*eslint-enable */
graphQLServer.use('/', graphqlHTTP({ schema: schema, graphiql: true }));
graphQLServer.listen(8080);
console.log("The GraphQL Server is running.")

var compiler = webpack({
  entry: "./index.js",
    output: {
        path: __dirname,
        filename: "bundle.js",
        publicPath: "/static/"
    },
    module: {
        loaders: [
            { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"
          }
        ]
    }
});

var app = new WebpackDevServer(compiler, {
  contentBase: '/public/',
  proxy: {'/graphql': `http://localhost:${8080}`},
  publicPath: '/static/',
  stats: {colors: true}
});

// Serve static resources
app.use('/', express.static('static'));
app.listen(3000);
console.log("The App Server is running.")
var path             = require('path');
var request          = require('request');
var WebpackDevServer = require('webpack-dev-server');
var webpack          = require('webpack');
var config           = require('./webpack.config');

var server = new WebpackDevServer(webpack(config), {
    contentBase : path.resolve(__dirname, 'build'),
    hot         : true,
    noInfo      : true
});

server.use(function (req, res, next) {
    var ext = path.extname(req.url);

    if ((ext === '' || ext === '.html') && req.url !== '/') {
        req.pipe(request('http://' + req.hostname + ':9000')).pipe(res);
    } else {
        next();
    }
});

server.listen(9000, function (err, result) {
    if (err) {
        console.log(err);
    }

    console.log('Listening at localhost:9000');
});
  gulp.task('dev', ['dev-preprocess'], () => {

    let webpackConfigPath = path.resolve(
      __dirname, 'webpack.dev.config.js'
    );

    if (argv.config) {
      webpackConfigPath = path.resolve(argv.config);
    }

    const config = require(webpackConfigPath);

    const devServerConfig = {
      contentBase: options.dist,
      hot: options.devServerDisableHot ? false : true,
      inline: true,
      stats: {
        colors: true
      },
      publicPath: config.output.publicPath,
      historyApiFallback: true
    };

    if (options.watchOptions) {
      devServerConfig.watchOptions = options.watchOptions;
    }

    if (options.devServerProxy) {
      devServerConfig.proxy = options.devServerProxy;
    }

    const server = new WebpackDevServer(
      webpack(config), devServerConfig
    );
    server.use('/', (req, res, next) => {

      const acceptLanguageHeader = req.headers['accept-language'];

      if (acceptLanguageHeader) {
        const acceptedLanguages = acceptLanguageHeader.match(
          /[a-zA-z\-]{2,10}/g
        );
        if (acceptedLanguages) {
          res.cookie('languages', JSON.stringify(acceptedLanguages));
        }
      }

      if (req.url.match(/.+\/img\//)) { // img
        res.redirect(301, req.url.replace(/.*\/(img\/.*)$/, '/$1'));
      } else if (req.url.match(/\/img\//)) { // img
        next();
      } else if (req.url.match(/.+\/video\//)) { // video
        res.redirect(301, req.url.replace(/.*\/(video\/.*)$/, '/$1'));
      } else if (req.url.match(/\/video\//)) { // video
        next();
      } else if (req.url.match(/.+\/font\//)) { // font
        res.redirect(301, req.url.replace(/.*\/(font\/.*)$/, '/$1'));
      } else if (req.url.match(/\/font\//)) { // font
        next();
      } else if (req.url.match(/.+\/.*\.[^\/]*$/)) { // file
        res.redirect(301, req.url.replace(/.*\/([^\/]*)$/, '/$1'));
      } else {
        next();
      }
    });

    // Always open on all ports unless overridden
    const host = options.devServerHost || '0.0.0.0';

    server.listen(options.devServerPort || 8080, host, (err) => {
      if (err) {
        console.error('[webpack-dev-server] failed to start:', err);
      } else {
        const openHost = (host === '0.0.0.0') ? 'localhost' : host;
        console.log('[webpack-dev-server] started: opening the app in your default browser...');
        const suffix = options.publicPath ? options.publicPath + '/' : '';
        const openURL = 'http://' + openHost + ':' + options.devServerPort + '/webpack-dev-server/' + suffix;
        gulp.src(path.join(options.dist, 'index.html'))
        .pipe(gulpOpen({
          uri: openURL
        }));
      }
    });

    server.app.get('/reload', (req, res) => {
      // Tell connected browsers to reload.
      server.sockWrite(server.sockets, 'ok');
      res.sendStatus(200);
    });

    server.app.get('/invalid', (req, res) => {
      // Tell connected browsers some change is about to happen.
      server.sockWrite(server.sockets, 'invalid');
      res.sendStatus(200);
    });

  });
/* globals __dirname */
'use strict';
var path             = require('path');
var proxy            = require('express-http-proxy');
var request          = require('request');
var WebpackDevServer = require('webpack-dev-server');
var webpack          = require('webpack');
var config           = require('./webpack.config.demo');

var server = new WebpackDevServer(webpack(config), {
    contentBase : path.resolve(__dirname, 'demo-build'),
    hot         : true,
    noInfo      : true
});

server.use('', proxy('http://localhost'));

server.use(function (req, res, next) {
    var ext = path.extname(req.url);

    console.log('req.hostname', req.hostname);

    if ((ext === '' || ext === '.html') && req.url !== '/') {
        req.pipe(request('http://' + req.hostname + ':9000')).pipe(res);
    } else {
        next();
    }
});

server.listen(9000, function (err, result) {
    if (err) {
  // Launch Relay by using webpack.config.js
  const relayServer = new WebpackDevServer(webpack(webpackConfig), {
    contentBase: '/build/',
    proxy: {
      '/graphql': `http://localhost:${config.graphql.port}`
    },
    stats: {
      colors: true
    },
    hot: true,
    historyApiFallback: true
  });

  // Serve static resources
  relayServer.use('/', express.static(path.join(__dirname, '../build')));
  relayServer.listen(config.port, () => console.log(chalk.green(`Relay is listening on port ${config.port}`)));
} else if (config.env === 'production') {
  // Launch Relay by creating a normal express server
  const relayServer = express();
  relayServer.use(historyApiFallback());
  relayServer.use('/', express.static(path.join(__dirname, '../build')));
  relayServer.use('/graphql', graphQLHTTP({ schema }));
  relayServer.listen(config.port, () => console.log(chalk.green(`Relay is listening on port ${config.port}`)));
}

relayServer.get('/auth/google',
  passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

// GET /auth/google/callback
//   Use passport.authenticate() as route middleware to authenticate the
Beispiel #23
0
graphQLServer.use('/', graphQLHTTP({schema, pretty: true}));
graphQLServer.listen(GRAPHQL_PORT, () => console.log(
  `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}`
));

// Serve the Relay app
const compiler = webpack({
  entry: path.resolve(__dirname, 'js', 'app.js'),
  module: {
    loaders: [
      {
        exclude: /node_modules/,
        loader: 'babel',
        test: /\.js$/,
      },
    ],
  },
  output: {filename: 'app.js', path: '/'},
});
const app = new WebpackDevServer(compiler, {
  contentBase: '/public/',
  proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
  publicPath: '/js/',
  stats: {colors: true},
});
// Serve static resources
app.use('/', express.static(path.resolve(__dirname, 'public')));
app.listen(APP_PORT, () => {
  console.log(`App is now running on http://localhost:${APP_PORT}`);
});
Beispiel #24
0
var compiler = webpack({
  entry: path.resolve(__dirname, 'app', 'app.js'),
  module: {
    loaders: [
      {
        exclude: /node_modules/,
        loader: 'babel',
        test: /\.js$/,
      }
    ]
  },
  output: {filename: 'app.js', path: '/'}
});
var app = new WebpackDevServer(compiler, {
  contentBase: '/public/',
  publicPath: '/app/',
  stats: {colors: true}
});
// Serve static resources
const allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}
app.use('/', express.static(path.resolve(__dirname, 'public')));
app.use(allowCrossDomain);
app.listen(APP_PORT, () => {
  console.log(`App is now running on http://localhost:${APP_PORT}`);
});
Beispiel #25
0
  // webpack-dev-middleware options
  quiet: false,
  noInfo: false,
  lazy: false,
  filename: "bundle.js",
  watchOptions: {
    aggregateTimeout: 300,
    poll: 1000
  },
  publicPath: "/assets/",
  headers: { "X-Custom-Header": "yes" },
  stats: { colors: true }
});

router.get('/demo', (req, res) => {
  // noCachedResult(res);
  res.send('Hello World!');
  // const useDeployedVersion = req.query.uselive;
  // const template = Twig.twig({ data: fs.readFileSync(path.join(__dirname, '../demo/hhd.html'), 'utf-8') });
  // res.send(template.render({
  //   hhd_type: req.params.hhd_type,
  //   // cdn_host: CDN_HOST,
  //   use_deployed_version: useDeployedVersion,
  // }));
});

server.use(router);
server.listen(devPort, "localhost", () => {
  console.log('Server start on port: ${devPort}');
});
// server.close();
Beispiel #26
0
  // Launch Relay by using webpack.config.js
  const relayServer = new WebpackDevServer(webpack(webpackConfig), {
    contentBase: '/build/',
    proxy: {
      '/graphql': `http://localhost:${config.graphql.port}`
    },
    stats: {
      colors: true
    },
    hot: true,
    historyApiFallback: true
  });

  // Serve static resources
  relayServer.use('/', express.static(path.join(__dirname, '../build')));

  //multer
  var storage = multer.diskStorage({
    destination: (req,file,cb) => {
      cb(null,path.resolve(__dirname, '../client/assets/uploads'))
    },filename: (req,file,cb) => {
      cb(null,file.originalname)
    }
  });

  relayServer.use('/uploads',multer({storage:storage}).any('image'),(req,res)=>{
    //  console.log(req.url);
    //  console.log(req.headers);
    //  console.log(req.body);
    //  console.log(req.files);
'use strict';

let path = require('path');
let webpack = require('webpack');
let WebpackDevServer = require('webpack-dev-server');
let config = require('./webpack.config.js').development;

let server = new WebpackDevServer(webpack(config), {
  contentBase: 'src/static/',
  stats: {
    // Do not show list of hundreds of files included in a bundle
    chunkModules: false,
    colors: true
  },
  publicPath: '/assets/',
  hot: true
});

server.use('/', (req, res) => res.sendFile(path.join(__dirname, '/src/static/index.html')));

server.listen(8080, 'localhost', err =>
  err ? console.error(err) : console.log('Listening on http://localhost:8080'));
Beispiel #28
0
));

// Serve the Relay app
var compiler = webpack({
  entry: path.resolve(__dirname, 'js', 'app.js'),
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        query: {stage: 0, plugins: ['./build/babelRelayPlugin']}
      }
    ]
  },
  output: {filename: 'app.js', path: '/'}
});
var app = new WebpackDevServer(compiler, {
  contentBase: '/public/',
  proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
  publicPath: '/js/',
  stats: {colors: true}
});
// Serve static resources
app.use('/', express.static('public'));
app.use('/node_modules/react', express.static('node_modules/react'));
app.use('/node_modules/react-relay', express.static('node_modules/react-relay'));
app.use('/node_modules/react-dom', express.static('node_modules/react-dom'));
app.listen(APP_PORT, () => {
  console.log(`App is now running on http://localhost:${APP_PORT}`);
});
Beispiel #29
0
  gulp.task('dev', ['preprocess'], function() {

    var env = assign({}, options.env, {
      __DEV_MODE__: true
    });

    var devWebpackConfig = assign({}, webpackConfig, options.webpack || {}, {
      entry: {
        app: ['webpack/hot/dev-server', './' + options.mainJs],
        styles: ['webpack/hot/dev-server', './' + options.mainScss]
      },

      output: {
        filename: 'index.js',
        path: dist,
        publicPath: '/'
      },

      devtool: 'inline-source-map',

      plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin(env)
      ]

    });

    if (options.webpack.devAlias) {
      devWebpackConfig.resolve.alias = options.webpack.devAlias;
    }

    if (!devWebpackConfig.resolve) {
      devWebpackConfig.resolve = {};
    }

    if (options.webpack.module && options.webpack.module.loaders) {
      webpackConfig.module.loaders.forEach(function(loader) {
        devWebpackConfig.module.loaders.push(loader);
      });
    }

    devWebpackConfig.resolve.extensions = ['', '.js', '.json', '.htm', '.html', '.scss'];

    var devServerConfig = {
      contentBase: dist,
      hot: true,
      inline: true,
      stats: {
        colors: true
      },
      publicPath: devWebpackConfig.output.publicPath,
      historyApiFallback: true
    };

    if (options.devServerProxy) {
      devServerConfig.proxy = options.devServerProxy;
    }

    var server = new WebpackDevServer(webpack(devWebpackConfig), devServerConfig);
    server.use('/', function(req, res, next) {

      if (req.url.match(/.+index.js$/)) {
        res.redirect(301, '/index.js');
      } else if (req.url.match(/.+\/img\//)) { // img
        res.redirect(301, req.url.replace(/.*\/(img\/.*)$/, '/$1'));
      } else if (req.url.match(/\/img\//)) { // img
        next();
      } else if (req.url.match(/.+\/font\//)) { // font
        res.redirect(301, req.url.replace(/.*\/(font\/.*)$/, '/$1'));
      } else if (req.url.match(/\/font\//)) { // font
        next();
      } else if (req.url.match(/.+\/.*\.[^\/]*$/)) { // file
        res.redirect(301, req.url.replace(/.*\/([^\/]*)$/, '/$1'));
      } else {
        next();
      }
    });
    server.listen(options.devServerPort || 8080, 'localhost', function(err) {
      if (err) {
        console.error('[webpack-dev-server] failed to start:', err);
      } else {
        console.log('[webpack-dev-server] started:', 'Browse to http://localhost:'+ options.devServerPort +'/webpack-dev-server/');
      }
    });

  });
  pretty: true,
  schema: Schema,
}));

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
  `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}`
));

const compiler = webpack(config);

app = new WebpackDevServer(compiler, {
  hot: true,
  historyApiFallback: true,
  contentBase: 'src',
  proxy: {'/graphql': `http://localhost:${GRAPHQL_PORT}`},
  publicPath: config.output.publicPath,
  stats: {
    colors: true,
    hash: false,
    timings: true,
    chunks: false,
    chunkModules: false,
    modules: false
  }
 });

app.use(webpackHotMiddleware(compiler));
app.listen(APP_PORT, () => {
  console.log(`App is now running on http://localhost:${APP_PORT}`);
});