WebPack和Express服务器不能一起工作

时间:2017-02-13 04:19:48

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

我很难找到解释如何将webpack连接到快速服务器应用程序的资源。我想在编写反应时使用webpack for babel来使用es6并使用它的热模块和廉价模块源映射。但是,webpack运行它自己的快速服务器,目前与我的快递应用程序冲突。我希望我的快递应用程序能够指示端口和路由,但仍然可以使用webpack。

有什么想法吗?

快递应用程序看起来像这样:

var express = require('express'),
    Sequelize = require('sequelize'),

/* 
set up sequelize ...
   app.route ...
*/

app.listen(port), function () {
  console.log('Express server listening on port ' + port
});

2 个答案:

答案 0 :(得分:1)

在编写React并使用其热模块和廉价模块源映射时,您不需要webpack-dev-server使用Webpack for Babel来使用ES2015。

开发环境中的React app的Webpack配置:

module.exports = {
  entry: {
    app: [
      'react-hot-loader/patch',
      'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
      'app/index.js,
    ],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ],
})

.babelrc看起来像这样:

{
  "presets": ["react", "es2015", "stage-0"],
  "env": {
    "development": {
      "plugins": ["react-hot-loader/babel"]
    }
  }
}

app/index.js

import { AppContainer} from 'react-hot-loader'
...
<AppContainer>
  <App />
</AppContainer>
...
if (module.hot) {
  module.hot.accept('./routes', () => {
    // Hot reloading
  })
}

server/index.js

import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from './webpack.dev.config'

const compiler = webpack(webpackConfig)

app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
}))

app.use(webpackHotMiddleware(compiler, {
  path: '/__webpack_hmr',
  heartbeat: 10000,
}))

我不确定它是否允许在这里引用我自己的回购,但请检查我的Github回购here以了解我如何整合React,Express,Webpack,HMR和Babel。< / p>

答案 1 :(得分:0)

我最终做的是使用了2种不同的配置,1用于使用webpack将服务器包装在一起,1用于将所有浏览器包装在一起,还运行webpack dev服务器进行热重新加载。

服务器webpack config又名webpack.node.config.js现在看起来像这样:

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = {};

// note the path.resolve(__dirname, ...) part
// without it, eslint-import-resolver-webpack fails
// since eslint might be invoked with different cwd
fs.readdirSync(path.resolve(__dirname, 'node_modules'))
    .filter(x => ['.bin'].indexOf(x) === -1)
    .forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });

// es5 style alternative
// fs.readdirSync(path.resolve(__dirname, 'node_modules'))
//     .filter(function(x) {
//         return ['.bin'].indexOf(x) === -1;
//     })
//     .forEach(function(mod) {
//         nodeModules[mod] = 'commonjs ' + mod;    
//     });

module.exports =

{
    // The configuration for the server-side rendering
    name: 'server',
    target: 'node',
    entry: './app/server/serverEntryPrototype.js',
    output: {
        path: './bin/',
        publicPath: 'bin/',
        filename: 'serverEntryPoint.js'
    },
    externals: nodeModules,
    module: {
        loaders: [
            { test: /\.js$/,

                loaders: [
                    // 'imports?document=this',

                    // 'react-hot',
                    'babel-loader'
                    //,'jsx-loader'
                ]
            },
            { test:  /\.json$/, loader: 'json-loader' },
        ]
    },
    plugins: [
    // new webpack.NormalModuleReplacementPlugin("^(react-bootstrap-modal)$", "^(react)$")
    // new webpack.IgnorePlugin(new RegExp("^(react-bootstrap-modal)$"))
    // new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};

浏览器webpack config又名webpack.browser.config.js现在看起来像这样:

var webpack = require('webpack');
var path = require('path');
var buildPath = path.resolve(__dirname, 'assets');
var fs = require('fs');


var commonLoaders = [
    { test: /\.js$/,

        loaders: [
            'react-hot',
            'babel-loader'
            //,'jsx-loader'
        ]
    }
];


module.exports =
{
    // Makes sure errors in console map to the correct file
    // and line number
    name: 'browser',
    devtool: 'eval',
    entry: [
        //'./bin/www.js',
        './app/index.js',
        'webpack/hot/dev-server',
        'webpack-dev-server/client?http://localhost:8081'  // WebpackDevServer host and port
    ],
    output: {
        path: buildPath,
        filename: '[name].js',
        // Everything related to Webpack should go through a build path,
        // localhost:3000/build. That makes proxying easier to handle
        publicPath: 'http://localhost:8081/assets/'
    },

    extensions: [
        '',
        '.jsx', '.js',
        '.json',
        '.html',
        '.css', '.styl', '.scss', '.sass'
    ],

    module: {

        loaders: [
            // Compile es6 to js.
            {
                test: /app\/.*\.jsx?$/,
                loaders: [
                    'react-hot',
                    'babel-loader'
                ]
            },

            ///app\/.*\.json$/
            { test:  /\.json$/, loader: 'json-loader' },

            // Styles
            { test: /\.css$/, loader: 'style-loader!css-loader' },
            { test: /\.s(a|c)ss$/, loader: 'style!css?localIdentName=[path][name]---[local]---[hash:base64:5]!postcss!sass' },

            // Fonts
            { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&minetype=application/font-woff' },
            { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader' }

            //{ test: /\.png$/, loader: 'url-loader?limit=100000' },
            //{ test: /\.jpg$/, loader: 'file-loader' }
        ],

        plugins: [
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NoErrorsPlugin()
        ]
    },

    postcss: [
        require('autoprefixer-core')
    ],

    devtool: 'source-map'
}
;