v8go
v8go copied to clipboard
Node modules
Hey, Does this work with node modules. If so how does it work? (Is there an example)
Yes if the node modules don't use node. I'd recommend bundling with https://esbuild.github.io/ then passing the bundle into v8go.
Yes if the node modules don't use node.
I think this means things like require
aren't available, because it's a higher-level Node API, not V8.
So, many modules will work, but if a module uses Node's APIs, they will fail at runtime. For example:
ReferenceError: require is not defined
I have not been able to find a work-around. So, I guess I'll have to pull Node itself into this project, run it as a subprocess.
I second what @matthewmueller suggested, that's what I use to run most npm packages on go. This should be out of scope for v8go.
As mentioned I also recommend esbuild for this. Just dont use stuff from node like fs
or crypto
etc and esbuild will bundle everything to a single file you can load.
Does single file builds with rollup work too?
I receive this error when trying to call an exported function bundle.js
Let's say I have deguasser.js (bundle file). And I have the following .go
code
func callDegausser(node string, options string) {
ctx := v8.NewContext()
importDegausser := `var degausser = require('./degausser.js');`
consoleLog := `console.log('WORKING!'); `
callDegausser := importDegausser + consoleLog + `degausser('` + "" + `','` + "" + `')`
// val, _ := ctx.RunScript(importDegausser + callDegausser, "degausser.js") // executes a script on the global context
val, err := ctx.RunScript(callDegausser, "degausser.js") // executes a script on the global context
log.Println("value: ", val, err)
}
I'm receving ReferenceError: require is not defined
error.
If I'm not including importDegausser string to 1rst argument I'm recieving ReferenceError: degausser is not defined
error`
@sb-bilal-dev-ev as I commented above,
require
is a Node API. It's not part of V8. It won't work in this context.
FTR, NodeJS supports CommonJS modules (const circle = require('./circle.js');
) and ECMAScript modules (import { circle } from './circle.mjs';
).
ECMAScript modules are natively supported by v8, but to use them in v8go a bit different API need to be used, e.g. v8::ScriptCompiler::CompileModule()
instead of v8::Script::Compile()
used in RunScript()
, plus potentially other changes.
CommonJS modules are not part of the language and could be implemented by bundlers as suggested above (independently from v8go).
ECMAScript modules would be a nice addition to v8go, but requires code/API changes.
I'm running into a similar issue.
I've bundled a small script that uses external modules with esbuild, but when importing packages (either through require or import keyword), I always get the SyntaxError: Unexpected identifier
or similar syntax errors, with no further details.
Is there any way to make this more verbose so I can understand what's going on?