Webpack:如何将客户端和服务器端组合成一个最终的捆绑包?

时间:2018-02-07 17:15:14

标签: express webpack

我已经有来自众多webpack配置和用例的眩晕并陷入僵局。最后,我构建了我的应用:react.js + express.js

服务器端现在只处理提交的表单数据并使用nodemailer发送电子邮件。在不久的将来,它会根据路线将数据注入html模板。

所以本地一切都运行正常,但我还没想出如何将最终生产包的客户端和服务器端与webpack结合起来。

以下是 packages.json:

的一部分
  "main": "src/index.js",
  "scripts": {
    "start": "start npm run start:client && start npm run start:server",
    "start:client": "webpack-dev-server",
    "start:server": "node server.js"
  },
  "proxy": "http://localhost:3000",

webpack 部分:

module.exports = {

    devtool: 'source-map',
    devServer: {
        historyApiFallback: true,
        contentBase: './src',
        proxy : {
            '/contact': 'http://localhost:3000'
          }     
    },

    entry: {
        vendor:  ['./src/js/plugins.js', 
            './src/js/classList.min.js'].map(function(link){ 
                return path.resolve(__dirname, link); 
            }),



        base: ['./src/css/animate.css', './src/css/outdatedbrowser.css'].map(function(link){ 
                return path.resolve(__dirname, link); 
            }),
        entry: ["babel-polyfill", './src/index.js']
    },
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].[chunkhash].js',
        publicPath: '/'
    },
    resolve: {
        extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
        modules: [
             path.join(__dirname, 'node_modules')
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('development')
        }),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            filename: 'vendor.[chunkhash].js',
            minChunks: Infinity
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                screw_ie8: true,
                conditionals: true,
                unused: true,
                comparisons: true,
                sequences: true,
                dead_code: true,
                evaluate: true,
                if_return: true,
                join_vars: true
            },
            output: {
                comments: false
            }
        }),
        new webpack.LoaderOptionsPlugin({
            options: {
                postcss: [
                    autoprefixer({
                        browsers: [
                            'last 3 version',
                            'ie >= 10'
                        ]
                    })
                ],
                context: staticSourcePath
            }
        }),
        new webpack.HashedModuleIdsPlugin(),
        new HtmlWebpackPlugin({
            template: path.join(__dirname, './public/index.html'),
            path: buildPath,
            excludeChunks: ['base'],
            filename: 'index.html',
            minify: {
                collapseWhitespace: true,
                collapseInlineTagWhitespace: true,
                removeComments: true,
                removeRedundantAttributes: true
            }
        }),
        new PreloadWebpackPlugin({
            rel: 'preload',
            as: 'script',
            include: 'all',
            fileBlacklist: [/\.(css|map)$/, /base?.+/]
        }),
        new ExtractTextPlugin({
            filename: '[name].[contenthash].css',
            allChunks: true
        }), 
        new StyleExtHtmlWebpackPlugin({
            minify: true
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new CompressionPlugin({
            asset: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
            threshold: 10240,
            minRatio: 0.8
        })
    ],
    module: {

        rules: [{
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env', 'react', 'stage-1'],
                    }
                },
                include: sourcePath
            }

        ]
    }

};

并提交结构

    dist <folder>
    node_modules <folder> ----   
    public <folder> ---- 
        index.html
    src <folder> ----   
        components <folder>
        ---css < folder > 
        ---fonts < folder >
        ---icons < folder >
        ---img < folder >
        ---js < folder > - third party JS
        ---.env    
        ---i18n.js    
        ---index.js
        ---myDetector.js
        ---sitemap.xml    
    server.js   
    package.json     
    package-lock.json 
    webpack.config.js

有人可以帮助配置以使其正常工作吗?

2 个答案:

答案 0 :(得分:0)

我正在与conifguration分享我的reactjs项目结构..

安装nodemon以观察服务器何时更改服务器端代码中的任何内容以及将您的es6或es7转换为es5

的babel

的package.json

"scripts": {
"server": "nodemon --watch server --exec babel-node -- server/index.js",
"start": "nodemon --watch server --exec babel-node -- server/index.js",
"test": "echo \"Error: no test specified\" && exit 1"

},

webpack.config.dev.js

let outputPath = path.join(__dirname);


export default {
// devtools: 'eval-source-map',
devtool: 'source-map',
entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, 'client/index.js'),
],
output: {
    path: outputPath,
    publicPath: "/",
    filename: 'bundle.js'
},
module:{        
    loaders:[
        {
            test: /\.js$/,                
            include: path.join(__dirname, 'client'),
            exclude: /(node_modules|bower_components)/,
            loaders: ['react-hot-loader','babel-loader'],                
        }
    ]
},
node: {
    fs: 'empty'
},
plugins: [
    new webpack.ProvidePlugin({
        "React": "react",
    }),
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
],
resolve: ['','.js']

}

项目结构

node_modules <folder> ----   
public <folder> ----   
    components <folder>
    ---css < folder > 
    ---fonts < folder >
    ---icons < folder >
    ---img < folder >
    ---js < folder > - third party JS
    ---.env    
    ---i18n.js    
    ---index.js
    ---myDetector.js
    ---sitemap.xml    
server
    ---index.html
    ---index.js
package.json     
package-lock.json 
webpack.config.dev.js

答案 1 :(得分:0)

嗯,我不知道为什么没有人回答,但答案很简单:他们不能捆绑在一起。服务器端应该在VPS上运行