score:0

The above answer is either old or has a couple issues. Here is a updated answer for webpack 5. This imports fonts and images from their respective folders.

const path = require("path");

module.exports = {
  target: "node",
  entry: {
    server: "./server.js"
  },
  output: {
    path: path.join(__dirname),
    filename: "[name]-packed.js",
  },
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|gif|svg|ico)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'img/'
            }
          }
        ]
      },
      {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                loader: "babel-loader"
            },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'fonts/'
            }
          }
        ]
      }
    ],
  },
};

score:6

You need a separate webpack config for your server

  1. Install this module to exclude node_modules:

    npm install --save webpack-node-externals 
    
  2. Create a separate webpack config for your server:

    module.exports = {    
      const path = require('path')
      const nodeExternals = require('webpack-node-externals')
    
      context: path.resolve(__dirname, 'directory of your server file'),
      entry: ['./filename of your server file'],
      output: {
        path: path.join(__dirname, 'directory of your bundled file'),
        filename: 'filename of your bundled file'
      },
      target: 'node',
      externals: [nodeExternals()],
      module: {
        rules: [
          {
            test: /\.(jpe?g|png|gif|svg|ico)$/i,
            use: 'url-loader?limit=8192'
          }
        ]
      }
    }
    
  3. Here's an example server webpack.config.js:

    module.exports = {    
      const path = require('path')
      const nodeExternals = require('webpack-node-externals')
    
      context: path.resolve(__dirname, 'src'),
      entry: ['./index.js'],
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
      },
      target: 'node',
      externals: [nodeExternals()],
      module: {
        rules: [
          {
            test: /\.(jpe?g|png|gif|svg|ico)$/i,
            use: 'url-loader?limit=8192'
          }
        ]
      }
    }
    
  4. If using the above webpack.config.js example, run webpack then the compiled server file:

    webpack
    node dist/bundle.js
    

Related Query

More Query from same tag