VM2 Usage with Webpack

663 views Asked by At

I've been having trouble using webpack with a typescript project that uses vm2.webpack --config webpack.config.js gives the following error:

ERROR in index.js from Terser Invalid function parameter [webpack://./node_modules/source-map-loader/dist/cjs.js!./node_modules/vm2/lib/main.js:1226,1][index.js:1262,21]

This is the minimal repro I've been testing with:

import { VM } from 'vm2';

export async function run(): Promise<void> {
    new VM();
}

By using the optimization: { minimize: false } } option in my webpack.config.js I was able to find the source of the error. In the vm2 package source code this block exists:

const HOST = {
    ...,
    require,
    ...
}

which gets webpacked as:

const HOST = {
    ...,
    __webpack_require__(952),
    ...
}

This clearly fails. I'm not sure what I else I can do here, is there a config somewhere I can change to

My webpack.config.js:

const path = require('path');

module.exports = {
    target: 'node',
    entry: './vm2index.ts',
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: 'commonjs',
    },

    // optimization: {
    //     minimize: false,
    // },

    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },

    devtool: 'source-map',

    mode: 'production',

    // Add the loader for .ts files.
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'awesome-typescript-loader',
                exclude: /node_modules/,
            },
            {
                enforce: 'pre',
                test: /\.js$/,
                loader: 'source-map-loader',
            },
        ],
    },

    stats: {
        warningsFilter: [
            "Module not found: Error: Can't resolve 'encoding'",
            "Cannot find SourceMap 'typescript.js.map'",
        ],
    }
};
0

There are 0 answers