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.