Webpack - How do you require an optional dependency in bundle (saslprep)

前端 未结 3 1988
[愿得一人]
[愿得一人] 2021-01-19 16:09

I am using webpack to bundle a number of back-end scripts into a single file during my deployment process.

When connecting to the MongoDB database there is an option

3条回答
  •  忘掉有多难
    2021-01-19 16:45

    Thanks to Brendan for steering me in the right direction. Ultimately the answer was found here: http://www.matthiassommer.it/software-architecture/webpack-node-modules/

    The key piece of information being:

    Webpack’s compiler converts the require() call to its own webpack_require(). At runtime it looks into its internal module registry.

    Following the steps outlined therein the resolution becomes:

    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/),
        ],
        externals: {
            "saslprep": "require('saslprep')"
        }
    };
    

    Please note that in my testing the quotes around "saslprep" do appear to berequired when importing externals.

提交回复
热议问题