Home > database >  How can I bundle up an npm package so I can import objects from it in a script?
How can I bundle up an npm package so I can import objects from it in a script?

Time:03-27

I would like to use tiptap for a project https://tiptap.dev/installation.

The instructions on the website state that after running npm install @tiptap/core @tiptap/starter-kit I can use the following code to set up a basic demo

import { Editor } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'

new Editor({
  element: document.querySelector('.element'),
  extensions: [
    StarterKit,
  ],
  content: '<p>Hello World!</p>',
})

I would like to wrap up tiptap core and tiptap starter-kit into a single JavaScript file which I can load and use in a HTML page such as

<html>
<body>
    <div ></div>

    <script src="bundle.js"></script>
    <script>
        new Editor({
            element: document.querySelector('.element'),
            extensions: [
                StarterKit,
            ],
            content: '<p>Hello World!</p>',
        })
    </script>
</body>
</html>

I have tried using webpack to create a single file using the following webpack.config.js file

const path = require('path');

module.exports = {
  entry: ['@tiptap/core', '@tiptap/starter-kit'],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    libraryTarget: 'umd', // make the bundle export
  },
};

This doesn't work however. The browser console returns

Uncaught ReferenceError: Editor is not defined at [some line reference here]

How can I bundle tiptap up and use just the bundle.js file in my HTML page and scripts?

CodePudding user response:

I solved this using https://rollupjs.org

Steps

Step 1. Create a new directory and run npm init --yes inside

Step 2. Install rollup from npm

npm install --global rollup @rollup/plugin-node-resolve @rollup/plugin-replace rollup-plugin-terser

Step 3. Install tiptap from npm

npm install @tiptap/core @tiptap/starter-kit

Step 4. Add a rollup.config.js file to the directory. File contents are:

import replace from "@rollup/plugin-replace";
import { terser } from "rollup-plugin-terser";

export default {
    input: "index.js",
    output: [
        {
            file: "tiptap-rollup.js",
            format: "iife",
            name: "window",
            extend: true
        },
        {
            file: "tiptap-rollup.min.js",
            format: "iife",
            name: "window",
            extend: true,
            plugins: [ terser() ]
        }
    ],
    plugins: [
        replace({
            "process.env.NODE_ENV": "'production'"
        }),
        nodeResolve()
    ]
};

Step 5. Run rollup -c from the command line in the new directory you created.

  • Related