After upgrading webpack to version 5 getting run time error: Buffer is not defined
Asked Answered
F

2

5

After migrating to webpack version= 5, I am getting run time error

Buffer is not defined. Reason: UNKNOWN at function_name (file_name:118)

while the build part goes through fine.

Webpack does it's build part but in my project I am also using sdk where rollup plugin is used to bundle javascript which bundles it into file_name.esm.js and then webpack bundles code from file_name.esm.js to another seperate file.

I can see after bundling javascript into a single file using rollup, the location responsible for this error to occur is where the "Buffer" variable is declared. It's like below after bundling code into file_name.esm.js =>

import { Buffer as Buffer$1 } from 'buffer';

at the same time I can also see that "Buffer$1" alias also been used as variable in file_name.esm.js but there is a code which is using "Buffer"variable also. So, this is why I think error has occured (i.e "Buffer is not defined").

But with previous webpack version (4), this line of code was working fine and "Buffer" variable was correctly referenced despite imported like this

import { Buffer as Buffer$1 } from 'buffer';

FILE structure/location => "file_name.js" location is "root/core/file_name.js"

My rollup.config is =>

import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import filesize from 'rollup-plugin-filesize';
import json from 'rollup-plugin-json';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';
import {uglify} from 'rollup-plugin-uglify';
const path = require('path');

import pkg from './package.json';

const {
    FORMAT = 'cjs',
} = process.env;

const isModule = FORMAT === 'cjs' || FORMAT === 'esm';

const dest = {
    cjs: pkg.main,
    esm: pkg.module,
    iife: 'dist/abc.iife.min.js',
};

const config = {
    input: 'src/index.js',
    external: ['buffer'],
    output: {
        format: FORMAT,
        file: dest[FORMAT],
        indent: false,
        globals: {
            'buffer': 'buffer',
        },
    },
    plugins: [
        json(),
        babel({
            exclude: /node_modules\/(?!(root\/core)\/).*/,
            runtimeHelpers: true,
        }),
        replace({
            TOKEN_VERSION: JSON.stringify(pkg.version),
            TOKEN_MEMBER: JSON.stringify('js-user'),
        }),
        filesize(),
    ],
};

if (isModule) {
    config.plugins.push(resolve());
    config.external = id => [...Object.keys(pkg.dependencies), 'core-js', 'regenerator']
        .some(dep => dep !== 'root/core' && id.includes(dep));
} else {
    config.output.name = 'xyz';
    config.plugins.push(
        resolve({
            preferBuiltins: false,
            browser: true,
            customResolveOptions: {
                moduleDirectory: path.resolve(__dirname, 'node_modules'),
            },
        }),
        globals(),
        builtins(),
        commonjs(),
        uglify({
            warnings: false,
        }));
}

export default config;

I am finding it hard to figure out if this is the webpack issue or rollup issue, it should be webpack because I have tested same code with webpack version 4, it is working fine. Could someone please suggest how can I resolve this.

Freer answered 8/4, 2021 at 17:58 Comment(1)
I found this Webpack 5 Node Polyfills Upgrade Cheatsheet to be very helpful gist.github.com/ef4/d2cf5672a93cf241fd47c020b9b3066aPrimrosa
Q
7

Webpack 4 used to shim Node globals like Buffer. Webpack 5 removed these polyfills: https://github.com/webpack/changelog-v5

To fix, you'll either need to not depend on Buffer or use a package like 'buffer' to resolve.

You can configure Webpack to use this like so:

new webpack.ProvidePlugin({
  Buffer: ['buffer', 'Buffer'],
})
Quotidian answered 4/6, 2021 at 8:11 Comment(1)
Worked like a charm. Thank youDivan
H
1

Ran into this too. Need to install the polyfills they once included.

  • if you haven't already and are using create-react-app to create the project, run npm run eject => input y when prompted
  • install the following dependencies npm i -D url stream-http buffer process https-browserify in ./config/webpack.config.js add the following in the resolve object
 fallback: {
      "http": require.resolve("stream-http"),
      "https": require.resolve('https-browserify'),
      "buffer": require.resolve('buffer'),
      "url": require.resolve("url/"),
    },

add the following in the plugins object *make sure you don't put it in one of the nested plugins objects

new webpack.ProvidePlugin({
          process: 'process/browser',
          Buffer: ['buffer', 'Buffer'],
}),
Humane answered 10/1, 2022 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.