title: Webpack - How do you require an optional dependency in bundle (saslprep)
body: <p>I am using webpack to bundle a number of back-end scripts into a single file during my deployment process.</p>
  
  <p>When connecting to the MongoDB database there is an optional dependency, which throws a warning if it is not included.</p>
  
  <pre><code>Warning: no saslprep library specified. Passwords will not be sanitized
  </code></pre>
  
  <p>In my development environment this error is easily resolved by installing the optional dependency.</p>
  
  <pre><code>npm install saslprep --save
  </code></pre>
  
  <p>However when bundling with webpack the optional dependency is not included and the warning persists in the production deployment. I can trace the cause of this easily enough, the mongodb library is requiring this as an optional dependency:</p>
  
  <pre class="lang-js prettyprint-override"><code>let saslprep;
  try {
    saslprep = require('saslprep');
  } catch (e) {
    // don't do anything;
  }
  </code></pre>
  
  <p>I have tried following the webpack documentation using shimming, externals, plugins and frankly am quite lost as to the correct approach to resolve this issue. Here is my current webpack.config file (attempting to require this as a plugin).</p>
  
  <pre class="lang-js prettyprint-override"><code>const path = require('path');
  const webpack = require('webpack');
  
  module.exports = {
      entry: './src/api/index.ts',
      target: 'node',
      mode: 'production',
      module: {
          rules: [
              {
                  test: /\.tsx?$/,
                  loader: 'ts-loader',
                  exclude: /node_modules/
              }
          ]
      },
      resolve: {
          extensions: ['.js', '.tsx', '.ts', '.json']
      },
      output: {
      filename: 'api.js',
          path: path.resolve(__dirname, 'dist'),
      },
      plugins: [
          new webpack.IgnorePlugin(/fsevents/),
          new webpack.IgnorePlugin(/blessed/),
          new webpack.ProvidePlugin({
              saslprep: path.resolve(__dirname, "node_modules/saslprep/index.js")
          })
      ],
  };
  </code></pre>
  
  <p>Thanks in advance.</p>