【问题标题】:Separate client and server in Webpack在 Webpack 中分离客户端和服务器
【发布时间】:2018-02-24 13:37:58
【问题描述】:

目标。配置应用,其中有:React、Webpack 和 MongoDB。

所以,我已经为 React 设置了 Webpack 并尝试导入 Mongoose。问题:React 客户端和 Mongoose - 服务器端,因此 Webpack 必须对两者都有配置。使用这个答案:https://stackoverflow.com/a/37391247/7479176 我尝试配置 Webpack。之后,我尝试在 server.jsx 文件中导入 Mongoose,但没有成功。

问题。如何配置 Webpack,以便我可以使用 MongoDB?

已编辑。我想出了如何摆脱警告(请参阅警告):

output: {
            filename: 'bundle.node.js',
            libraryTarget: 'commonjs',
            path: path.resolve(__dirname, 'dist')
        },
        externals: [
            /^(?!\.|\/).+/i
        ],

但是,当我将代码添加到 server.jsx(请参阅 server.jsx)时,它没有在控制台中记录消息。

Webpack 配置:

const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')

module.exports = [
    {
        entry: {
            index: './src/app/app.jsx'
        },
        devtool: 'inline-source-map',
        devServer: {
            port: 3000,
            host: 'localhost',
            historyApiFallback: true,
            noInfo: false,
            stats: 'minimal',
            hot: true, // Tell the dev-server we're using HMR
            contentBase: path.resolve(__dirname, './dist'),
            publicPath: '/'
        },
        plugins: [
            new webpack.NamedModulesPlugin(),
            new webpack.HotModuleReplacementPlugin(), // Enable HMR
            new CleanWebpackPlugin(['dist']),
            new HtmlWebpackPlugin({
                template: './src/index.html',
                filename: 'index.html',
                inject: 'body'
            })
        ],
        output: {
            filename: 'bundle.js',
            path: path.resolve(__dirname, 'dist')
        },
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: ['babel-loader']
                },
                {
                   test: /\.css$/,
                   use: ['style-loader', 'css-loader'] 
                }
            ]
        }
    },
    {
        entry: {
            index: './src/server/server.jsx'
        },
        target: 'node',
        output: {
            filename: 'bundle.node.js',
            path: path.resolve(__dirname, 'dist')
        },
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: ['babel-loader']
                }
            ]
        }
    }
]

server.jsx:

import mongoose from 'mongoose'
import '../config/database.js'

mongoose.Promise = global.Promise
mongoose.connect(config.database)
// check connection
mongoose.connection.once('open', () => console.log('Connected to MongoDB'))
// check for db errors
mongoose.connection.on('error', err => console.log(err))

警告:

WARNING in ./node_modules/mongoose/lib/drivers/index.js
10:13-49 Critical dependency: the request of a dependency is an expression

WARNING in ./node_modules/require_optional/index.js
82:18-42 Critical dependency: the request of a dependency is an expression

WARNING in ./node_modules/require_optional/index.js
90:20-44 Critical dependency: the request of a dependency is an expression

WARNING in ./node_modules/require_optional/index.js
97:35-67 Critical dependency: the request of a dependency is an expression

WARNING in ./node_modules/es6-promise/dist/es6-promise.js
Module not found: Error: Can't resolve 'vertx' in 'D:\Projects\JavaScriptProjects\pizzaday\node_modules\es6-promise\dist'
 @ ./node_modules/es6-promise/dist/es6-promise.js 131:20-30
 @ ./node_modules/mongodb/lib/mongo_client.js
 @ ./node_modules/mongodb/index.js
 @ ./node_modules/mongoose/lib/index.js
 @ ./node_modules/mongoose/index.js
 @ ./src/server/server.jsx

【问题讨论】:

  • 恕我直言,客户端和服务器确实应该在不同的项目中,或者如果您坚持将两者放在同一个根项目文件夹中,至少应该在不同的文件夹层次结构中。就我个人而言,我总是将后端分开,并且只为 webpack 开发服务器传递代理选项,以便在开发期间“通过”到单独运行的服务器。在现实生活中,前端和后端通常具有解耦的部署周期。所以这也是需要考虑的。

标签: node.js mongodb webpack


【解决方案1】:


解决方案。我将 webpack-dev-middleware 和 webpack-hot-middleware 与基本的 Express 服务器一起使用。我尝试在 webpack-dev-server 上使用 React 启动 MongoDB,这是主要问题。


我根据 Neil Lunn 的建议在单独的文件夹中创建了新的 server.js,并使用中间件设置了基本的 Express 服务器,并将 Webpack 配置拆分为 3 个单独的文件 common、dev 和 prod。


server.js 中的这段代码帮助我将服务器和客户端与 Webpack 结合在一起运行:

app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
}))

app.use(webpackHotMiddleware(compiler))

新的 Webpack 配置(webpack.common.js):

const webpack = require('webpack')
const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: {
        app: [
            'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=2000&reload=true',
            './src/index.jsx'
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            template: './index.html',
            filename: 'index.html',
            inject: 'body'
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
               test: /\.css$/,
               use: ['style-loader', 'css-loader'] 
            }
        ]
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多