Truffle Webpack: Can't resolve 'module' in require-from-string

Viewed 773

This happens during compilation when the require call is made in :

The error points to the line where this is declared:

var Module = require('module');

this is in the index.js of require-from-string Actually I can put that require statement anywhere it continues to cause an error.

I have installed module using npm and which does exist in my node_modules.

my webpack.config.js :

const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack')
const standardOptions = require('./package.json').standard

const environment = process.env.NODE_ENV || 'development'
const $ = {}
const modulePattern = /(node_modules|bower_components)/

module.exports = {
  node: {
    fs: 'empty'
  },
  entry: './app/javascript/app.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'app.js'
  },
  plugins: [
    // Copy our app's index.html to the build folder.
    new CopyWebpackPlugin([
      { from: './app/index.html', to: "index.html" }
    ])
  ],
  module: {
    rules: [
      {
       test: /\.css$/,
       use: [ 'style-loader', 'css-loader', "postcss-loader" ]
      }
    ],
    loaders: [
      { test: /\.json$/, use: 'json-loader' },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015'],
          plugins: ['transform-runtime']
        }
      }
    ]
  }
}
2 Answers

I ran into this when trying to use solc in the browser with Next.js. I solved it with a Webpack resolve fallback based on this answer to an open issue in the require-from-string repository.


Here is what I did:

I added a resolve fallback for module to my next.config.js config, so Webpack is able to resolve an import to 'module', which is what the error is caused by.

module.exports = {
    // more Next.js config ...
    webpack(config, { isServer }) {
        if (isServer) {
            return config;
        }

        return {
            ...config,
            resolve: {
                ...config.resolve,
                fallback: {
                    ...config.resolve?.fallback,
                    module: require.resolve('./src/polyfills/module.js'),
                },
            },
        };
    },
};

If you are not using Next.js, I assume the webpack.config.js would look something like this:

module.exports = {
  resolve: {
    fallback: {
      module: require.resolve('./src/polyfills/module.js'),
    },
  },
  // more webpack config ...
};

Note that this is a Webpack 5 config, Webpack 4 may be a little different.

The polyfill (src/polyfills/module.js) is as simple as:

module.exports = module.constructor;

I have no idea if this is a valid polyfill for the NodeJS module API, but in my case it did the job.

Related