Laravel javascript require perfect-scrollbar - javascript

I try to require the jquery pulgin perfect-scrollbar to my laravel javascript. So I have runed
npm install perfect-scrollbar
In Line 1 of my Javascript file (located under ressources/assets/javascript/material-dashboard/myfile.js) I require the plugin with this attempt
require('perfect-scrollbar');
The myscript.js is required to the app.js with require('./material-dashboard/myscript.js')
Now the browser console tell me
Uncaught TypeError: $(...).perfectScrollbar is not a function
The assets are compiled with
npm run dev
The content of myscript.js
require('perfect-scrollbar');
(function() {
isWindows = navigator.platform.indexOf('Win') > -1 ? true : false;
if (isWindows) {
// if we are on windows OS we activate the perfectScrollbar function
$('.sidebar .sidebar-wrapper, .main-panel').perfectScrollbar();
$('html').addClass('perfect-scrollbar-on');
} else {
$('html').addClass('perfect-scrollbar-off');
}
})();
What is wrong?
Thanks for your help!

Just to simplify your job, under bootstrap.js file that handles
require('perfect-scrollbar');
simply change it to
window.PerfectScrollbar = require('perfect-scrollbar').default; and you will be good to go. Only answers questions if using compiling assets in laravel with bootstrap.js

As per the docs, to initialise an element with the plugin you should do something like the following:
import PerfectScrollbar from 'perfect-scrollbar';
new PerfectScrollbar(".sidebar .sidebar-wrapper");
new PerfectScrollbar(".main-panel");
If you want to use require instead of import you would do something like:
let PerfectScrollbar = require('perfect-scrollbar').default;
Lastly, it doesn't look like the plugin is meant to work with jQuery out of the box, however, if you want to use with jQuery like you are in your post you could do the following:
import PerfectScrollbar from 'perfect-scrollbar';
$.fn.perfectScrollbar = function (options) {
return this.each((k, elm) => new PerfectScrollbar(elm, options || {}));
};
$('.sidebar .sidebar-wrapper, .main-panel').perfectScrollbar();

Related

Ruby on Rails 6 Webpack with Javascript libraries

I am building a new project in Rails 6. I have a front-end library I want to use (#tarekraafat/autocomplete.js) that is installed by yarn and exists in my node_modules directory, but is not being made available to other JS code in the browser. Here is what I have set up currently:
/package.json:
"dependencies": {
"#tarekraafat/autocomplete.js": "^8.2.1"
}
/app/javascript/packs/application.js:
import "#tarekraafat/autocomplete.js/dist/js/autoComplete.min.js"
/app/views/.../example.html.erb
<script type="text/javascript">
window.onload = () => {
new autoComplete({
[...]
});
};
</script>
I am getting an error in the browser pointing to the new autoComplete():
Uncaught ReferenceError: autoComplete is not defined
Some reading seems to indicate that I need to modify the /config/webpack/environment.js file, in which I have tried various versions of the following with no luck (including restarting the dev server):
/config/webpack/environment.js:
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
autoComplete: 'autocomplete.js'
})
);
module.exports = environment
First, what do I need to do to add this library so it can be used correctly? Second, as someone who has not directly used webpack previously, what is the function of adding this definition to the environments.js file, and why don't I need to do it for some libraries (bootstrap, popper) but I do for others (jquery, and maybe autocomplete.js)?
In Webpacker, the usage of this library would be as follows:
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
new autoComplete(...)
// app/javascript/packs/application.js
import "../src/any_file"
This alone does not import the autoComplete variable into the global scope. To do that, the simplest thing is assign the variable to window from within your webpack dependency graph.
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
window.autoComplete = autoComplete
As an aside, you don't need to use the ProvidePlugin configuration for this library. The ProvidePlugin says: “add this import to all files in my dependency graph.” This might be helpful for something like jQuery to make legacy jQuery plugins work in webpack. It is not necessary to make your autocomplete lib work

Require.js define object is somehow being inserted to my code - gulp.js

I'm running a gulp-concat script, which concats jquery, slick-carousel, t.js and my index.js files.
const pack = () => {
return gulp.src(['./node_modules/jquery/**/jquery.js', './node_modules/slick-carousel/**/slick.js', './assets/js/t.js-master/t.js', './js/index.js'])
// .pipe(gulp_babel({
// 'presets': ['#babel/env'],
// 'plugins': ["transform-remove-strict-mode"]
// }))
.pipe(gulp_concat('main.js'))
// .pipe(gulp_uglify())
.pipe(gulp.dest('./build'));
}
As you can see, I removed any pipes that might be causing the issue. The only task running is gulp-concat. (index.js is all in ES5 and I'm running on latest version of firefox, no need for babel atm) When I open my page, however, I get the error
Uncaught ReferenceError: define is not defined
Looking at main.js, I found a define object at the end of the jquery section - but only in the concatinated file, not the jquery in node_modules. I didn't add this, and I'm not using require.js as far as I know:
define( [
"./core",
"./selector",
"./traversing",
"./callbacks",
"./deferred",
"./deferred/exceptionHook",
"./core/ready",
"./data",
"./queue",
"./queue/delay",
"./attributes",
"./event",
"./event/focusin",
"./manipulation",
"./manipulation/_evalUrl",
"./wrap",
"./css",
"./css/hiddenVisibleSelectors",
"./serialize",
"./ajax",
"./ajax/xhr",
"./ajax/script",
"./ajax/jsonp",
"./ajax/load",
"./core/parseXML",
"./core/parseHTML",
"./effects",
"./effects/animatedSelector",
"./offset",
"./dimensions",
"./deprecated",
"./exports/amd",
"./exports/global"
], function( jQuery ) {
"use strict";
return jQuery;
} ); // jQuery seems to end here
How is this extra code being added, and how might I avoid it? I'm also using browserSync, but don't think that's related.
I've just checked the source of jQuery and there is a file:
https://github.com/jquery/jquery/blob/3.5.1/src/jquery.js
So what you need to do is to simply exclude it and it should fix the issue :)

Integrating React components with Pux - where does require() come from?

The Pux documentation tells me to use require() in the browser. Where does that function come from and how do I use it?
Background:
I'm trying to integrate the Quill editor with my web application that uses purescript-pux.
Following the Pux documentation I created a file MyEditor.js like this:
// module MyEditor
var React = require("react");
var Pux = require("purescript-pux");
var MyEditor = React.createClass({
displayName: "MyEditor",
onTextChange: function onTextChange(value) {
this.setState({ text: value });
},
render: function render() {
return React.createElement(ReactQuill, { value: this.state.text,
onChange: this.onTextChange });
}
});
exports.fromReact = Pux.fromReact(MyEditor);
and a file MyEditor.purs as follows:
module MyEditor where
import Pux.Html (Html, Attribute)
foreign import fromReact :: forall a. Array (Attribute a) -> Array (Html a) -> Html a
I then use MyEditor.fromReact [value p.description] in my Html Action and the code compiles, but the browser complains about ReferenceError: require is not defined.
I'm not very familiar with the javascript ecosystem. I'm aware that several libraries providing a require() function exist, but which one do I use with Pux and how?
require is the NodeJS way of importing modules, it's not supported in the browser so you'll need to run your project through a bundler like browserify or webpack to produce a bundle that the browser can understand.
If you are using the pulp build tool it's as simple as running
pulp browserify --to app.js
and then loading app.js in your html through a script tag.
pulp browserify documentation: https://github.com/bodil/pulp#commonjs-aware-builds
In addition to Christophs answer (but can't comment since comments don't allow code blocks):
Using Thermite 4.1.1 this worked for me:
add a package.json file with:
{
"dependencies": {
"react": "^0.14",
"react-dom": "^0.14"
}
}
run npm install
from then on pulp browserify --optimise gets the whole shebang packaged.
This is really badly documented and I opened an issue about that on purescript-react.

How to properly load local AMD modules with jspm/system.js

I am having a really hard time using local AMD modules in an Aurelia project that uses es6, JSPM, and system.js. I am hoping someone out there can help me configure my project to enable me to import/load my AMD modules and use them in my project. The local AMD style modules are in a format similar to the following:
define
(['require',
'lib/alerts/STARTSTOP',
'lib/alerts/STOPPED',
...
],
function( require, STARTSTOP, STOPPED, ... ) {
return {
alert: function( data ) {
var type = data.type;
var ev = data.event;
var cls = require( 'lib/alerts/' + ev );
return new cls( data );
}
};
});
When I try to import/load this module into an es6 module I am running into the following error: Uncaught TypeError: Unexpected anonymous AMD define.. I get this error when trying to load the module in either of the following ways:
System.import('lib/alerts/AlertFactory').then( (m) => {
console.log( m );
});
or
import AlertFactory from 'lib/alerts/AlertFactory.js';
I have also made sure to add the following script to my index.html:
<script>
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
</script>
In addition to the above I have also added a meta format property to my config.js file, but that hasn't seemed to help either.
meta: {
...
"lib/alerts/*.js": {
"format": "amd"
}
}
Does anyone have any ideas on why I am running into the error I am seeing and how to properly load my modules? I appreciate any help/insight you can offer.
UPDATE
I finally realized that the main issue here is that I'm trying to use existing AMD modules in and Aurelia project, and the default Aurelia gulp build assumes that all code is written in ES6 and not mixed with AMD. That's why I'm having issues. Vanilla jspm/system.js handle a mix of module formats, but Aurelia does not out of the box.
Just put your AMD modules out of src so babel will not be able to transpile it. Here is working solution I use to import jquery modules:
First, I have local_packages folder in project root and I have jquery module local_packages/somelib/js/mymodule.js
Then in config.js
paths: {
...
"local/*": "local_packages/*",
}
map: {
...
"somelib": "local/somelib",
"somelib1": "/local_packages/somelib1",
}
And finally my import looks like: import 'somelib/js/mymodule';

How to install fastclick with ember-cli?

I've got an ember-cli project. I've used bower to install fastclick and have added it to my brocfile.
Now I'm trying to initialise it. In my app.js file I've added:
import FastClick from 'bower_components/fastclick/lib/fastclick';
But this gives me an error in the console: "Uncaught TypeError: Cannot read property 'default' of undefined". The inspector shows the following generated code:
["ember","ember/resolver","ember/load-initializers","bower_components/fastclick/lib/fastclick","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var Ember = __dependency1__["default"];
var Resolver = __dependency2__["default"];
var loadInitializers = __dependency3__["default"];
var FastClick = __dependency4__["default"]; # chrome highlights this line
I assume the problem is that fastclick isn't compatible with the ES6 loader that ember-cli uses. I don't have requirejs, so how can I install fastclick into my project? Docs are at https://github.com/ftlabs/fastclick.
I've also tried adding this to index.html, but it doesn't have any effect when I build an iOS app:
$(function() {
FastClick.attach(document.body);
});
With Ember-cli v0.0.42
Install fastclick with bower
bower install fastclick --save
In your Brocfile.js, add the following above module.exports = app.toTree();
app.import('bower_components/fastclick/lib/fastclick.js');
Then in your app.js you can add
var App = Ember.Application.extend({
...
ready: function(){
FastClick.attach(document.body);
}
});
You'll also need to add "FastClick":true to your .jshintrc file's predefs, to prevent it from complaining. More info in the docs about Managing Dependencies.
You can also use ember-cli-fastclick :)
OK the jquery version didn't work, but putting the following in my index.html file did:
window.addEventListener('load', function() {
FastClick.attach(document.body);
}, false);

Categories

Resources