简体   繁体   中英

Using Webpack to bundle node_modules and client side js with express

I'm relatively new to webpack and a bit confused about how to set it up, I'm using express as a web server and most of my code is server-side code.

First I tried something like this by reading through the docs:

module.exports = {
  context: __dirname + "/assets",
  target: 'node',
  entry: "../app.js",
  output: {
    filename: "bundle.js"
  }
};

This gave me the undesired result of generating a bundle.js with all of the dependencies with all of the server side code for the entire project.

Lets say I have 4 pages.

  1. page1 (uses jquery.js, script1.js)
  2. page2 (uses jquery.js)
  3. page3 (uses jquery.js, script1.js)
  4. page4 (does not use js)

I would like to create a webpack that compiles all of these to serve to the client via a webpage. I have installed jquery via npm install jquery meaning it is in my node_modules directory. script1.js is a script file made for the project and stored in a /assets/js directory.

How would you do something like this?

So after messing around with this for a few hours you can reference node modules by their name, the following will bundle the jquery node module to the file jquery.js in the root project directory.

  module.exports = {
    target: 'node',
    entry: {
     jquery: "jquery"
    },
    output: {
      filename: '[name].js',
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM