javascriptwysiwyg

Wysimark on plain JS


There is Wysimark - WYSIWYG Markdown Editor. I need add it to page with plain JS, using <script> tag.

I installed it with pnpm add @wysimark/standalone

For some reason, it is not written in the docs how to add to page using the script tag, although it is written that the solution is Plain JS (or is it something else?)

I do it like this

index.html

<html>
    <body>
        <div id="editor-container"></div>
        <script defer type=module src='index.js'></script>
    </body>
</html>

index.js

import { createWysimark } from "@wysimark/standalone"

const container = document.getElementById("editor-container")

const wysimark = createWysimark(container, {
  initialMarkdown: "# Hello World",
})

An error appears

Uncaught SyntaxError: The requested module '/cmwysiwig/node_modules/@wysimark/standalone/.dist/browser/index.cjs.js' does not provide an export named 'createWysimark' (at index.js:1:10)

What am I doing wrong?


Solution

  • This issue is caused by the package not exposing the createWysimark function in the CommonJS (CJS) build and the ESM build not inlining/bundling the imports. You can solve this by using a bundler to re-bundle/package the code like so:

    import { buildForBrowser } from '@jsheaven/easybuild'
    
    await buildForBrowser({
      entryPoint: '$theWysimarkStandaloneDistFile.js', // still having import statements
      outfile: './dist/javascript/index.js', // imports are resolved/bundled in now; this file can be used directly via <script> inject; but still needs to be shipped via a CDN or webserver
      dts: false,
      debug: process.argv.indexOf('--dev') > -1,
      esBuildOptions: {
        logLevel: 'error',
      },
    })
    

    So for now, as the author has several issues open on his repo regarding this, there is a quick fix using the wysimark-standalone npm package, which does exactly that. You can load the resulting bundled code via unpkg directly:

    <html>
      <head>
        <script src="https://www.unpkg.com/wysimark-standalone/dist/javascript/index.cjs.js"></script>
      </head>
      <body>
        <div id="editor-container"></div>
        <script>
          const container = document.getElementById("editor-container")
          // createWysimark is available on window now
          const wysimark = createWysimark(container, {
            initialMarkdown: "# Hello World",
          })
        </script>
      </body>
    </html>