miltone
miltone

Reputation: 4764

use basic js library (not node module) with symfony webpack encore

I have a Symfony 5 project with Webpack Encore tools for manage assets.

I would like to use external JS library in my project : Cachu Slider Library

I added this in my webpack.config.js file :

.addEntry('cachu-js', './assets/js/cachu-slider.min.js')
.addStyleEntry('cachu-css', './assets/css/cachu-slider.min.css')

Those files seems to be good imported in my public/build directory symfony

My finally entrypoints.json is :

{
  "entrypoints": {
    "app": {
      "js": [
        "/build/runtime.js",
        "/build/app.js"
      ],
      "css": [
        "/build/app.css"
      ]
    },
    "cachu-js": {
      "js": [
        "/build/runtime.js",
        "/build/vendors~cachu-js.js",
        "/build/cachu-js.js"
      ]
    },
    "background": {
      "js": [
        "/build/runtime.js",
        "/build/background.js"
      ]
    },
    "cachu-css": {
      "js": [
        "/build/runtime.js"
      ],
      "css": [
        "/build/cachu-css.css"
      ]
    }
  }
}

And in my app.js file I have wrote this :

// import Cachu from './cachu-slider.min'

let Cachu = require('./cachu-slider.min');

let slider = new Cachu(document.querySelector('.cachu__container'));

slider.run();

My web browser seems to be good loaded library files for Cachu (js and css). My webpack compil seems to be good with generate nothing errors. But My console on the browser tell me that :

TypeError: Cachu is not a constructor

How I can use a basic js library file with this config (Symfony, Webpack Encore) ? Why It does not know Cachu for instancied but import statment generate nothing error ?

Upvotes: 1

Views: 1184

Answers (1)

Alexander Dimitrov
Alexander Dimitrov

Reputation: 974

You don’t need to create an entry point for the third party library.

Instead in App.js just import and use it.

If the library is installed via yarn or npm it should be in node_modules, is the import path should be:

import Cachu from ‘cachu-slider’;

Or to import the minified versions:

import Cachu from ‘cachu-slider/dist/cachu-slider.min’;

import ‘cachu-slider/dist/cachu-slider.min.css’;

Upvotes: 1

Related Questions