2

I understand how to include the package using yarn. The problem I am running into is actually with any javascript package I have installed. But I am using cropperjs as a specific example.

yarn install cropperjs

installs the relevant files and can be found under /node_modules/cropperjs

import Cropper from "cropperjs"
or
require("cropperjs")

and I think it is adding the correct package to the webpack because when i do a search in the packaged json I see references to cropper in the application js file

/* harmony import */ var cropperjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! cropperjs */ "./node_modules/cropperjs/dist/cropper.js");
/* harmony import */ var cropperjs__WEBPACK_IMPORTED_MODULE_4___default =

/#PURE/webpack_require.n(cropperjs__WEBPACK_IMPORTED_MODULE_4__);

but i have no idea how to read it, so I'm assuming that the relevant js is being added to the global application.js file.

However, I cannot access Cropper in the debugger nor when calling to setup the objects.

I've tried reading as much documentation as I could, but I for the life of me cannot figure out how to access function calls in included or required javascript libraries via webpacker.

This was trivial to do in the asset pipeline, and I could revert to that, but it seems this is the direction we are supposed to be all moving towards, but even books like Modern Front End Development use TS and I'm a neophyte with js and its making things even more complicated.

Can someone please help me find an explanation that clarifies the correct way to add js packages for rails 6 using webpacker so that the added package is accessible globally? I had the same problem using jQuery and cut and paste some code to make it accessible

import $ from 'jquery';
global.jQuery = $;
global.$ = $;

but honestly don't understand how to do something similar for cropper or any other js package.

Kenny
  • 21
  • 1
  • 1
  • Perhaps my own answer that I am still working on to my own very similar question may help https://stackoverflow.com/questions/61569415/how-to-integrate-jqtree-in-rails-6-with-webpacker-tree-is-not-a-function – jamesc Jun 29 '20 at 05:44

1 Answers1

0

Webpack does not expose any modules to the global scope by default. This includes any modules you write and bundle with webpack or any modules you've installed with yarn in node_modules.

There are several ways you can add modules to the global scope.

You could assign individual references to the global scope, which is window or global (the two are the same in webpack). Just as you've done for jQuery, you can do for Cropper:

import Cropper from 'cropperjs'
window.Cropper = Cropper

Assigning references to the global object should be adequate for small projects or for limited use cases.

rossta
  • 11,394
  • 1
  • 43
  • 47