Home > Back-end >  Use a Node module in a public JS file in a Laravel app
Use a Node module in a public JS file in a Laravel app

Time:04-30

I want to use https://github.com/ueberdosis/tiptap in my Laravel app.

I did an npm install @tiptap/core @tiptap/starter-kit and the modules are installed fine and visible in my node_modules folder. Then, I added

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

to my resources/js/apps.js and ran an npm run dev. I can see some tiptap code in my public/js/app.js file.

I would like to instantiate a tiptap class from another public JS file:

  • which didn't come out of webpack
  • which I declared with a <script type="module" src="{{ asset('js/tiptap.js') }}"></script> in my Blade file
  • which contains following:
import { Editor } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'

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

but I just get a Uncaught TypeError: Failed to resolve module specifier "@tiptap/core". Relative references must start with either "/", "./", or "../". in the console.

So yeah, wrong path for the import most likely. I tried to change it to './app.js@tiptap/core' and other variations but always end up with a 404 Not found.

I feel like I'm maybe doing the wrong way maybe, I don't know. Would you guys have any tips on how to do that ?

CodePudding user response:

You can't access a package from outside because when webpack built it for you it encapsulates the file as a bundle so to be able to access it you could create another js file in the resources/js after that include it inside the app.js to be bundled with webpack like this

// hello.js
console.log("welcome from hello script")

// app.js
require('./hello.js')
  • Related