#How do I import buffer properly?

1 messages · Page 1 of 1 (latest)

bold pumice
#

Having a Vite React project which require buffer (for image processing) and it works fine in dev locally. However during build I have encountered this error:

'Buffer' is not exported by node_modules/buffer/index.js, imported by node_modules/.vite/deps_build-build/axios.js
file: /Users/.../node_modules/.vite/deps_build-build/axios.js:1:9
1: import { Buffer as Buffer } from 'Buffer';
            ^    

I searched for answer and found this post:
https://stackoverflow.com/questions/72773373/buffer-is-not-exported-by-vite-browser-externalbuffer
And I did some changes in my vite.config.ts:

import inject from '@rollup/plugin-inject';

... 
build: {
      outDir: 'build',
      sourcemap: true,
      commonjsOptions: {
        esmExternals: true,
        include: [],
      },
      rollupOptions: {
        plugins: [inject({Buffer: ['Buffer', 'Buffer']})],
      },
    },

what should I do to make it work properly?

bold pumice
#

I've also tried the polyfill approach, and it gave even more errors.

Error: Build failed with 2 errors:
error: Could not read from file: /Users/...node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-buffer-polyfill_.js
error: Could not read from file: /Users/.../node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js
``` and 

'default' is not exported by node_modules/.vite/deps_build-build/axios.js, imported by src/server/service.ts

bold pumice
#

Alright, so I used the OP's method (that inject approach), and if I also have

rollupOptions: {
        plugins: [inject({Buffer: ['Buffer', 'Buffer']})],
        external: ['Buffer'],
      },

I would pass the CI or can run the build. But the final deployment gave this error:

Uncaught TypeError: Failed to resolve module specifier "Buffer". Relative references must start with either "/", "./", or "../".

So how can I fix this properly?