How to Polyfill node core modules using vite - javascript

It seems that vite does not do automatic polyfills anymore - vite 4.0.0
How do you guys go about this? I have tried multiple variations of what I could find over the internet and none of them seems to be solid.
✘ [ERROR] The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/#esbuild-plugins/node-globals-polyfill/_buffer.js" cannot be marked as external
✘ [ERROR] The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/#esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js" cannot be marked as external
Build failed with 2 errors:
error: The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/#esbuild-plugins/node-globals-polyfill/_buffer.js" cannot be marked as external
error: The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/#esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js" cannot be marked as external
my config
// yarn add --dev #esbuild-plugins/node-globals-polyfill
import { NodeGlobalsPolyfillPlugin } from "#esbuild-plugins/node-globals-polyfill";
// yarn add --dev #esbuild-plugins/node-modules-polyfill
import { NodeModulesPolyfillPlugin } from "#esbuild-plugins/node-modules-polyfill";
// You don't need to add this to deps, it's included by #esbuild-plugins/node-modules-polyfill
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
export default {
resolve: {
alias: {
// This Rollup aliases are extracted from #esbuild-plugins/node-modules-polyfill,
// see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
// process and buffer are excluded because already managed
// by node-globals-polyfill
util: "rollup-plugin-node-polyfills/polyfills/util",
sys: "util",
events: "rollup-plugin-node-polyfills/polyfills/events",
stream: "rollup-plugin-node-polyfills/polyfills/stream",
path: "rollup-plugin-node-polyfills/polyfills/path",
querystring: "rollup-plugin-node-polyfills/polyfills/qs",
punycode: "rollup-plugin-node-polyfills/polyfills/punycode",
url: "rollup-plugin-node-polyfills/polyfills/url",
string_decoder: "rollup-plugin-node-polyfills/polyfills/string-decoder",
http: "rollup-plugin-node-polyfills/polyfills/http",
https: "rollup-plugin-node-polyfills/polyfills/http",
os: "rollup-plugin-node-polyfills/polyfills/os",
assert: "rollup-plugin-node-polyfills/polyfills/assert",
constants: "rollup-plugin-node-polyfills/polyfills/constants",
_stream_duplex: "rollup-plugin-node-polyfills/polyfills/readable-stream/duplex",
_stream_passthrough: "rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough",
_stream_readable: "rollup-plugin-node-polyfills/polyfills/readable-stream/readable",
_stream_writable: "rollup-plugin-node-polyfills/polyfills/readable-stream/writable",
_stream_transform: "rollup-plugin-node-polyfills/polyfills/readable-stream/transform",
timers: "rollup-plugin-node-polyfills/polyfills/timers",
console: "rollup-plugin-node-polyfills/polyfills/console",
vm: "rollup-plugin-node-polyfills/polyfills/vm",
zlib: "rollup-plugin-node-polyfills/polyfills/zlib",
tty: "rollup-plugin-node-polyfills/polyfills/tty",
domain: "rollup-plugin-node-polyfills/polyfills/domain",
},
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: "globalThis",
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill(),
],
},
},
};

I encountered the same issue "cannot be marked as external" when working with the bip39 package and getting error because of buffer not defined. I tried many stuffs so not sure how what I solved, but here is my configuration (working with svelteKit):
In vite.config.js:
import { sveltekit } from '#sveltejs/kit/vite';
import type { UserConfig } from 'vite';
const config: UserConfig = {
plugins: [sveltekit()],
resolve: {
alias: {
// polyfills
Buffer: 'vite-compatible-readable-buffer',
stream: 'vite-compatible-readable-stream',
util: 'rollup-plugin-node-polyfills/polyfills/util',
}
}
};
export default config;
In layout.ts:
import { Buffer as BufferPolyfill } from 'buffer'
declare var Buffer: typeof BufferPolyfill;
globalThis.Buffer = BufferPolyfill
In app.html:
<script>
/**
* this is a hack for error: global is not defined
*/
var global = global || window
</script>
I hope it helps. I'm new to svelte and I don't 100% know what I'm doing :p

Related

Vite 4 fails to emit JS bundle

I have upgraded from Vite 2.9.13 to 4.0.4, and to be on theme with the version number Vite can not find the entry point for JS anymore. It emits everything correctly except the JavaScript bundle which ends up like below. No error messages or anything.
// main-12345678.js
import "./reset-12345678.js";
const customfonts = "";
const style = "";
//# sourceMappingURL=main-12345678.js.map
// Where is the rest of my bundle? ¯\_(ツ)_/¯
Any ideas as to why I get a blank page and the almost empty JS bundle above?
vite --mode staging --config vite.config.js build
// vite.config.js
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
export default defineConfig(({ command, mode }) => ({
plugins: [react()],
root: "client",
build: {
sourcemap: mode !== "production",
minify: mode !== 'production' ? false : 'esbuild',
outDir: "dist/publish",
rollupOptions: {
input: {
main: new URL("./client/index.html", import.meta.url).pathname,
other: new URL("./client/other.html", import.meta.url).pathname,
},
},
},
}));

Storybook Canvas: 'ReferenceError: react is not defined'

Newbie to Storybook here.
I'm trying to integrate Storybook into my Gatsby front end. However, when trying to preview the test components in Storybook Canvas I get the following error:
react is not defined
ReferenceError: react is not defined
at react-dom/client (http://localhost:6006/main.iframe.bundle.js:1970:18)
at webpack_require (http://localhost:6006/runtime~main.iframe.bundle.js:28:33)
at fn (http://localhost:6006/runtime~main.iframe.bundle.js:339:21)
at webpack_require.t (http://localhost:6006/runtime~main.iframe.bundle.js:106:38)
I'm able to see the component preview in Storybook Docs but not in Storybook Canvas.
Link to repository:
https://github.com/akarpov91/gatsby-tutorial
Try adding the following snippet in your main.js:
module.exports = {
// ...
babel: async (options) => ({
...options,
presets: [
...options.presets,
[
'#babel/preset-react', {
runtime: 'automatic',
},
'preset-react-jsx-transform'
],
],
}),
};
Apparently, #storybook/react adds #babel/preset-react without runtime: 'automatic' property
I have had the same problem, try copying this into your .storybook/main.js config. Hope this works for you too.
module.exports = {
// You will want to change this to wherever your Stories will live
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.#(js|jsx|ts|tsx)"],
addons: ["#storybook/addon-links", "#storybook/addon-essentials"],
framework: "#storybook/react",
core: {
builder: "webpack5",
},
webpackFinal: async config => {
// Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/]
// Use installed babel-loader which is v8.0-beta (which is meant to work with #babel/core#7)
config.module.rules[0].use[0].loader = require.resolve("babel-loader")
// Use #babel/preset-react for JSX and env (instead of staged presets)
config.module.rules[0].use[0].options.presets = [
require.resolve("#babel/preset-react"),
require.resolve("#babel/preset-env"),
]
config.module.rules[0].use[0].options.plugins = [
// Use #babel/plugin-proposal-class-properties for class arrow functions
require.resolve("#babel/plugin-proposal-class-properties"),
// Use babel-plugin-remove-graphql-queries to remove graphql queries from components when rendering in Storybook
// While still rendering content from useStaticQuery in development mode
[
require.resolve("babel-plugin-remove-graphql-queries"),
{
stage: config.mode === `development` ? "develop-html" : "build-html",
staticQueryDir: "page-data/sq/d",
},
],
]
return config
},
}

'Buffer' is not exported by __vite-browser-external:buffer

I'm getting this build error with vite and sveltekit using adapter-node
I'm not sure why it won't build since it relies on node to server the client.
dev works fine
'Buffer' is not exported by __vite-browser-external:buffer
I tried polyfills but they don't work.
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
webworkers: true,
}),
NodeModulesPolyfillPlugin()
]
}
},
build: {
minify: true,
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill()
]
}
}
I solved it by adding the right aliases (including buffer and process) to config.vite.ts. That's how mine looks like:
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
import tsconfigPaths from 'vite-tsconfig-paths'
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill'
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'
export default defineConfig({
plugins: [react(), tsconfigPaths()],
server: {
port: 3001,
open: true
},
resolve: {
alias: {
// This Rollup aliases are extracted from #esbuild-plugins/node-modules-polyfill,
// see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
util: 'rollup-plugin-node-polyfills/polyfills/util',
sys: 'util',
events: 'rollup-plugin-node-polyfills/polyfills/events',
stream: 'rollup-plugin-node-polyfills/polyfills/stream',
path: 'rollup-plugin-node-polyfills/polyfills/path',
querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
url: 'rollup-plugin-node-polyfills/polyfills/url',
string_decoder:
'rollup-plugin-node-polyfills/polyfills/string-decoder',
http: 'rollup-plugin-node-polyfills/polyfills/http',
https: 'rollup-plugin-node-polyfills/polyfills/http',
os: 'rollup-plugin-node-polyfills/polyfills/os',
assert: 'rollup-plugin-node-polyfills/polyfills/assert',
constants: 'rollup-plugin-node-polyfills/polyfills/constants',
_stream_duplex:
'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
_stream_passthrough:
'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
_stream_readable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
_stream_writable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
_stream_transform:
'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
timers: 'rollup-plugin-node-polyfills/polyfills/timers',
console: 'rollup-plugin-node-polyfills/polyfills/console',
vm: 'rollup-plugin-node-polyfills/polyfills/vm',
zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
tty: 'rollup-plugin-node-polyfills/polyfills/tty',
domain: 'rollup-plugin-node-polyfills/polyfills/domain',
buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',
process: 'rollup-plugin-node-polyfills/polyfills/process-es6'
}
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true
}),
NodeModulesPolyfillPlugin()
]
}
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
// #ts-ignore
rollupNodePolyFill(),
]
}
}
})
build: {
rollupOptions: {
plugins: [inject({ Buffer: ['Buffer', 'Buffer'] })],
},
},
This works with npm i -D buffer

Uncaught ReferenceError: process is not defined after upgrading from vue cli v4 to v5

I'm working on an app where I've updated the frontend to use vue cli v5 from v4 and am getting a runtime error: Uncaught ReferenceError: process is not defined. Process.version is referenced in the jsonwebtoken library I'm using. See below:
Uncaught ReferenceError: process is not defined error
jsonwebtoken reference
I had a few pollyfill module related errors during compilation which I fixed below due to vue cli v5 using webpack 5:
fallback: {
crypto: require.resolve('crypto-browserify'),
buffer: require.resolve('buffer'),
util: require.resolve('util'),
stream: require.resolve('stream-browserify')
}
In my webpack config file I've tried adding/setting the process.env variable:
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': ''
}),
new Dotenv({ systemvars: true })
],
Has anyone run into a similar issue upgrading to vue cli v5? Thanks!
Try that:
const webpack = require('webpack');
const {defineConfig} = require('#vue/cli-service');
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
//process: {env: {}},
plugins: [
// fix "process is not defined" error:
// (do "npm install process" before running the build)
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
resolve: {
fallback: {
http: require.resolve("stream-http"),
https: require.resolve("https-browserify"),
crypto: require.resolve("crypto-browserify"),
stream: require.resolve("stream-browserify"),
os: require.resolve("os-browserify/browser"),
url: require.resolve("url"),
assert: require.resolve("assert"),
},
},
}
});

Nextjs import external components from parent directory

I have external directory common and I would like to import react components from that directory into web-static. In web-static I am using nextjs.
Currently I having this error:
Module not found: Can't resolve 'react' in '/Users/jakub/Sites/WORK/wilio-web-common/common/src/#vendor/atoms'
I added these lines to next.config.js:
const babeRule = config.module.rules[babelRuleIndex];
if (babeRule && babeRule.test) {
babeRule.test = /\.(web\.)?(tsx|ts|js|mjs|jsx)$/;
if (babeRule.include) {
babeRule.include = [
...babeRule.include,
resolve(__dirname, "../common/src/#vendor"),
];
}
}
config.resolve.alias = {
...config.resolve.alias,
"#vendor": resolve(__dirname, "../common/src/#vendor")
};
My tsconfig.json file:
"paths": {
"#vendor/*": ["../common/src/#vendor/*"]
}
Webpack can resolve these components but can't resolve installed packages in these components.
../common/src/#vendor/atoms/Test.js
Module not found: Can't resolve 'react' in '/Users/user1/Sites/WORK/web-app/common/src/#vendor/atoms'
Do I need to include this directory also in webpacks config.externals? Current nextjs webpack externals
-----
options.isServer: false
[ 'next' ]
-----
-----
options.isServer: true
[ [Function] ]
-----
How can be this done? Thanks for any help
Starting in Next.js 10.1.2, you can use the currently experimental externalDir option in next.config.js:
module.exports = {
experimental: {
externalDir: true,
},
};
Note that for React components to work, I also had to declare the root package.json as a yarn workspace:
{
// ...
"private": true,
"workspaces": ["next-js-directory"],
// ...
}

Categories