【问题标题】:WebPack and Express server not working togetherWebPack 和 Express 服务器不能一起工作
【发布时间】:2017-07-01 00:00:11
【问题描述】:

我很难找到解释如何将 webpack 连接到快速服务器应用程序的资源。我想在编写反应时使用 webpack for babel 使用 es6,并使用它的 hot-module 和cheap-module-source-map。但是,webpack 运行它自己的 express 服务器,并且目前与我的 express 应用程序冲突。我希望我的 express 应用程序能够指定端口和路由,但仍然可以获得使用 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
});

【问题讨论】:

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


    【解决方案1】:

    你不需要 webpack-dev-server 来使用 Webpack for Babel 在编写 React 时使用 ES2015 并使用它的 hot-module 和 Cheap-module-source-map。

    开发环境中 React 应用的 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,
    }))
    

    我不确定是否可以在这里引用我自己的 repo,但请查看我的 Github repo here 了解我如何集成 React、Express、Webpack、HMR 和 Babel。

    【讨论】:

    【解决方案2】:

    我最终做的是我使用了 2 种不同的配置,1 用于使用 webpack 将服务器内容打包在一起,1 用于将所有浏览器内容打包在一起并运行 webpack 开发服务器以进行热重载。

    服务器 webpack 配置又名 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 配置又名 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'
    }
    ;
    

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 2017-12-15
      • 2018-01-14
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      相关资源
      最近更新 更多