如何使Webpack和Node协同工作?

时间:2016-09-03 10:39:17

标签: node.js webpack webpack-dev-server

我计划在前端使用ES6模块,所以我在Webpack上进行了实验。但是,我很难做到ff:work

  1. 客户端发生更改时的热重新加载
  2. 服务器端发生变化时热重新加载(在webpack之前,我正在使用nodemon .并且没有问题)
  3. 在终端中丢失debug / console.log信息,因为它打印webpack状态而服务器上没有任何内容,例如我的自定义“Server running ....”日志。
  4. 下面的设置我试图通过npm start运行。每次我做出任何改变,我都必须再次运行npm start

    的package.json

    {
      "name": "socket-io-chat",
      "version": "1.0.0",
      "description": "",
      "main": "server.js",
      "scripts": {
        "start": "npm run build",
        "build": "webpack -d && webpack-dev-server --hot --inline --watch && node --watch",
        "build:prod": "webpack -p && webpack-dev-server"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "cors": "^2.7.1",
        "express": "*",
        "socket.io": "*"
      },
      "devDependencies": {
        "babel-core": "^6.14.0",
        "babel-loader": "^6.2.5",
        "babel-preset-es2015": "^6.14.0",
        "babel-preset-stage-2": "^6.13.0",
        "nodemon": "^1.10.2",
        "webpack": "^1.13.2",
        "webpack-dev-server": "^1.15.1"
      }
    }
    

    webpack.config.js

    var path = require("path");
    var debug = process.env.NODE_ENV !== "production";
    var webpack = require('webpack');
    var SRC_DIR = path.join(__dirname, "public");
    var DIST_DIR = path.join(__dirname, "public/js/dist");
    
    var config = {
        context: __dirname,
        devtool: debug ? "inline-sourcemap" : null,
        entry: {
          guest : path.join(SRC_DIR, "entry-guest.js"),
          authenticated : path.join(SRC_DIR, "entry-authenticated.js")
        },
        output: {
        path: DIST_DIR,
        filename: "[name].js"
      },
      modules: {
        loaders: [
          {
            test: /\.js?/,
            include: SRC_DIR,
            loader: "babel-loader",
            query: {
              presets: ["es2015", "stage-2"]
            }
          }
        ]
      },
      plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
      ],
      devServer: {
        https: false,
        contentBase: SRC_DIR,
        stats: 'errors-only',
        port: 3000
      }
    };
    
    module.exports = config;
    

    server.js

    //create server
    var express = require('express');
    var cors = require('cors');
    var app = express();
    
    app.use(cors());
    
    console.log('here');
    
    var server = require('http').createServer(app);
    
    //prepare socket io, make it listen to server
    var io = require('socket.io').listen(server);
    users = [];
    connections = [];
    
    var port = process.env.PORT || 3000;
    server.listen(port);
    console.log(`Server running *:${port}`);
    
    //routing
    app.get('/', function(req, res) {
      res.sendFile(__dirname + '/public/index.html');
    });
    
    //open a connection
    io.sockets.on('connection', function(socket) {
      connections.push(socket);
      console.log('Connected: %s sockets connected:', connections.length);
    
      //...more codes here
    });
    

1 个答案:

答案 0 :(得分:0)

在您的webpack配置文件中,您可以尝试使用“热模块更换”插件

除了已经实施的Nodemon之外,还应该在更改时重新加载客户端和服务器。

plugins: [
   new webpack.HotModuleReplacementPlugin(),
   new webpack.DefinePlugin({
      'process.env': {
         NODE_ENV: '"development"'
       }
   })
],

这是利用HotModuleReplacement的示例Webpack配置。

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://localhost:3001',
    'webpack/hot/only-dev-server',
    path.resolve(__dirname, 'client', 'index.jsx')
  ],
  output: {
    path: path.resolve(__dirname, 'public'),
    publicPath: '/',
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"'
      }
    })
  ],
  resolve: {
    modules: [path.resolve(__dirname, 'node_modules')],
    extensions: ['*', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
            {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
        'file-loader'
        ]
      },
    ]
  },
    devServer: {
    port: 3001,
    contentBase: path.resolve(__dirname, 'public'),
    hot: true,
    historyApiFallback: true
  },
  devtool: 'source-map'
};