what is the most reasonable way apply webpack to a full-stack node app?

早过忘川 提交于 2020-06-24 03:58:27

问题


i've been studying up on webpack for a couple of weeks now, and i've seen many examples of front end setups, and probably just this one setup for a backend.

i'm trying to setup a react app with a node back-end (e.g. express, koa, hapi, etc) where i would need at least one transpilation step for the back-end (e.g. babel, coffeescript, etc), and i think it would be nice to use webpack there for consistency vs adding another build mechanism to the mix (e.g. gulp, grunt, etc).

it would also be great if i could make changes to the backend and have the server restart automatically (watch style).

i'm wondering if the best way to do that is to basically have two distinct project setups with their own package.json and webpack.config files. maybe nest the back-end one under a server folder in the top level project folder, and use one or more script directives in the top level package.json file to control the two.

i guess i might have to proxy one server to the other to avoid CORS issues as well.

looking for any guidance from those more webpack battle tested than i for a decent setup.

regards, tony.


回答1:


Easiest way is to split this into two tasks: a build step that outputs to a folder (e.g. 'server'), then watch the output folder for changes and restart server task.

1. Build task

This can be in the same webpack.config as client building code - you can export an array and webpack will watch all of them. Example webpack.config.js (top half is for server)

module.exports = [
{
  name: 'server code, output to ./server',
  entry: './index.js',
  output: {
    filename: './server/index.js'
  },
  target: 'node'
},
{
  name: 'client side, output to ./public',
  entry: './app.js',
  output: {
    filename: './public/app.js'
  }
}
];

2.Watch Step

For the watch step, nodemon monitor changes and restart. Otherwise you could add a watch task to your server.js manually using something like fs.watch or node-watch.



来源:https://stackoverflow.com/questions/30686531/what-is-the-most-reasonable-way-apply-webpack-to-a-full-stack-node-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!