parser: Can't seem to load browser friendly parser

If trying to load the browser friendly parser I get an empty object.

const parser = require('@solidity-parser/parser');
console.log(parser) // { ParserError: [Getter], parse: [Getter], tokenize: [Getter], visit: [Getter] } 

const parser = require('@solidity-parser/parser/dist/index.iife');
console.log(parser) // {}

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 16 (3 by maintainers)

Most upvoted comments

In webpack (>5?) you can skip the fs check by:

  resolve: {
    fallback: {
      "fs": false,
      "path": false,
    }
  }

You can also get past (typeof BROWSER !== "undefined") without editing the src by using Webpack DefinePlugin

   ...
  plugins: [
    new webpack.DefinePlugin({
      BROWSER: true,
    }),

I am working on a project that runs purely on browser and I wasn’t able to load this package. With a little bit of debugging I found the following code was the cause of the problem in src/tokens-string.js:

if (typeof BROWSER !== "undefined") {
  module.exports = require('./antlr/Solidity.tokens')
} else {
  module.exports = require('fs')
    .readFileSync(require('path').join(__dirname, './antlr/Solidity.tokens'))
    .toString()
}

For some reason, BROWSER variable is always undefined and this causes problems on the bundler side because there is no fs module on browser. So what I did was to replace BROWSER with window object to detect if the package is running in the browsers context:

if (typeof window !== "undefined") {
  module.exports = require('./antlr/Solidity.tokens')
} else {
  module.exports = require('fs')
    .readFileSync(require('path').join(__dirname, './antlr/Solidity.tokens'))
    .toString()
}

With this change, everything worked flawlessly. Now I need to mention that I am pretty new to whole Typescript, bundler stuff so maybe what I did was unnecessary or unrelated to the issue raised here. But still, I wanted to share it here in case it might help someone.