rafi16jan / micropython-wasm

A WebAssembly module built from the official MicroPython port
https://www.npmjs.com/package/micropython
MIT License
46 stars 8 forks source link

Webpack: Can't resolve 'fs' #4

Open tessereth opened 5 years ago

tessereth commented 5 years ago

I tried pulling in this npm package and compiling it with webpack but I get the following errors:

ERROR in ./node_modules/micropython/index.js
Module not found: Error: Can't resolve 'fs' in './micropython_example/node_modules/micropython'
 @ ./node_modules/micropython/index.js 21:9-22
 @ ./assets/js/app.js
 @ ./assets/js/index.js

ERROR in ./node_modules/micropython/lib/micropython.js
Module not found: Error: Can't resolve 'fs' in './micropython_example/node_modules/micropython/lib'
 @ ./node_modules/micropython/lib/micropython.js 39:15-28 80:13-26 179:28-41 3005:23-36
 @ ./node_modules/micropython/index.js
 @ ./assets/js/app.js
 @ ./assets/js/index.js

This appears to be because webpack is not detecting that it can never go down the "node-only" path and still trying to require fs. If I add typeof __webpack_require__ !== 'function' on every branch that requires fs, everything works. But I don't know enough about webpack to be confident such changes are a good idea and/or they wouldn't break it for someone else.

You can see my webpack version and config and a working example at https://github.com/tessereth/micropython_wasm_example.

tessereth commented 5 years ago

Reading through various issues (including https://github.com/webpack/webpack/issues/7352), looks like you can get around issues in the emscripten generated javascript (lib/micropython.js) by adding an ignore plugin to the webpack config:

  plugins: [
    ...
    new webpack.IgnorePlugin(/^fs$/),
  ],

This does not fix the issue in index.js. I'm pretty sure this code: https://github.com/rafi16jan/micropython-wasm/blob/0672c9ea7b04217cea9f8cec7246989b30cf5140/index.js#L20-L22 does not work as intended. When running in the brower, webpackJsonp is undefined even when it was originally built with webpack. Perhaps using typeof window === 'undefined' would be better?