React服务端渲染原理解析与实践(3)

const Path = require('path'); module.exports = { mode: 'development', entry: './src/client/index.js', output: { filename: 'index.js', path: Path.resolve(__dirname, 'public') }, module: { rules: [ { test: /.js?$/, loader: 'babel-loader', exclude: /node_modules/, options: { presets: ['react', 'stage-0', ['env', { targets: { browsers: ['last 2 versions'] } }]] } } ] } }

package.json文件中添加一条打包client目录的命令

{ ... "scripts": { "dev": "npm-run-all --parallel dev:**", "dev:start": "nodemon --watch build --exec node \"./build/bundile.js\"", "dev:build": "webpack --config webpack.server.js --watch", "dev:build": "webpack --config webpack.client.js --watch", } ... }

这样我们启动的时候会编译client运行的文件。再去访问页面的时候就可以绑定好事件了。

下面我们对上面工程的代码进行整理,上面webpack.server.js和webpack.client.js文件有很多重复的地方,我们可以使用webpack-merge插件对内容进行合并。

webpack.base.js

module.exports = { module: { rules: [ { test: /.js?$/, loader: 'babel-loader', exclude: /node_modules/, options: { presets: ['react', 'stage-0', ['env', { targets: { browsers: ['last 2 versions'] } }]] } } ] } }

webpack.server.js

const Path = require('path'); const NodeExternals = require('webpack-node-externals'); // 服务端运行webpack需要运行NodeExternals, 他的作用是将express这类node模块不被打包到js里。 const merge = require('webpack-merge'); const config = require('./webpack.base.js'); const serverConfig = { target: 'node', mode: 'development', entry: './src/server/index.js', output: { filename: 'bundle.js', path: Path.resolve(__dirname, 'build') }, externals: [NodeExternals()], } module.exports = merge(config, serverConfig);

webpack.client.js

const Path = require('path'); const merge = require('webpack-merge'); const config = require('./webpack.base.js'); const clientConfig = { mode: 'development', entry: './src/client/index.js', output: { filename: 'index.js', path: Path.resolve(__dirname, 'public') } }; module.exports = merge(config, clientConfig);

src/server中放置的是服务端运行的代码,src/client放置的是浏览器端运行的js。

到此这篇关于React服务端渲染原理解析与实践的文章就介绍到这了,更多相关React服务端渲染内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsgszs.html