1
votes

I'd like to provide a runtime assert to all code in a Sapper application I'm making.

Edited:

Bringing the assert module works for server builds, but not for client builds, showing either of these 500 error messages in the browser:

  • import { strict as sa } from 'assert';

    Module specifier does not start with ...

    With this, client build shows a warning: 'assert' is imported by src/assert.js, but could not be resolved – treating it as an external dependency

  • const sa = require("assert").strict;

    Can't find variable: require

    With this, client build passes. :/

My rollup.config.js and package.json.

Disclaimer: I am new to Svelte and Sapper and have no idea what should be done, here. My goal is not only to get it to work, but also understand what went wrong (i.e. learn about the Sapper/Svelte packaging mechanisms).


Original description:

This should be simple. Define a global high up (the app can import or require the assert and place it available). In practise, I'm still confused.

I've thought about setting window.assert directly (a bit harsh?) and passing the value as a parameter to those components actually needing it (but parameter passing looks difficult).

This is a case of dependency injection in the way that I'd like there to be an assert and the lower code doesn't care, which flavour.

Note: console.assert won't do because it only prints out the message. Chrome has an option for making it break. I may consider that.

2

2 Answers

1
votes

Server side

The assert module is built into node. For example, if you import it in src/server.js and call assert(false, "whoops") that works fine.

Client side

Since there isn't a browser version of assert module, you'll need to install the npm package assert as a devDependency and then include it in your bundle.

This is done by importing it in src/client.js:

// src/client.js
import assert from 'assert'

....

Now you can import it inside .svelte files too:

<!-- Example.svelte -->
<script>
  import assert from assert

  assert(false, "dang it")
</script>
0
votes

I moved on from Sapper to svelte-filerouter and the problems are gone.🙂 Here are the details (please comment if it works for you).

In .svelte or .js files:

import { assert } from 'assert';

In rollup.config.js:

...
   plugins: [
      resolve( {
         preferBuiltins: true,
         mainFields: ['browser'],
         dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
      })
   ]

I framed this based on this issue of rollup-plugin-node-resolve.


I don't know why the 500's I got in Sapper are now gone. A lot is different if one works with Sapper as the foundation vs. just Svelte.