How to import jquery using ES6 syntax? - javascript

I'm writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for the style.
index.js
import * as stylesheet from '../assets/styles/app.scss';
import * as jquery2 from '../dist/scripts/jquery.min';
import * as jquery3 from '../node_modules/jquery/dist/jquery.min';
console.log($('my-app'));
index.html
<!DOCTYPE html>
<html lang="fr">
<head>
<body>
<script src="dist/app.js"></script>
</body>
</html>
Project structure
.
├── app/
│ ├── index.js
├── assets/
├── dist/
│ ├── scripts/
│ │ ├── jquery.min.js
├── index.html
├── node_modules/
│ ├── jquery/
│ │ ├── dist/
│ │ │ ├── jquery.min.js
├── package.json
└── tests/
package.json
…
"scripts": {
"build:app": "browserify -e ./app/index.js -o ./dist/app.js",
"copy:jquery": "cpy 'node_modules/jquery/dist/jquery.min.js' ./dist/scripts/",
…
},
"devDependencies": {
"babel-core": "6.3.x",
"babel-preset-es2015": "6.3.x",
"babelify": "7.2.x",
"cpy": "3.4.x",
"npm-run-all": "1.4.x",
"sassify": "0.9.x",
"semantic-ui": "2.1.x",
…
},
"browserify": {
"transform": [
[ "babelify", { "presets": [ "es2015"]}],
[ "sassify", { "auto-inject": true}]
]
}
Question
Using classic <script> tag to import jquery works fine, but I'm trying to use the ES6 syntax.
How do I import jquery to satisfy semantic-ui using ES6 import syntax?
Should I import from the node_modules/ directory or my dist/ (where I copy everything)?

index.js
import {$,jQuery} from 'jquery';
// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;
First, as #nem suggested in comment, the import should be done from node_modules/:
Well, importing from dist/ doesn't make sense since that is your distribution folder with production ready app. Building your app should take what's inside node_modules/ and add it to the dist/ folder, jQuery included.
Next, the glob –* as– is wrong as I know what object I'm importing (e.g. jQuery and $), so a straigforward import statement will work.
Last you need to expose it to other scripts using the window.$ = $.
Then, I import as both $ and jQuery to cover all usages, browserify remove import duplication, so no overhead here! ^o^y

Based on the solution of Édouard Lopez, but in two lines:
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;

You can create a module converter like below:
// jquery.module.js
import 'https://code.jquery.com/jquery-3.6.0.min.js'
export default window.jQuery.noConflict(true)
This will remove global variables introduced by jQuery (jQuery & $) and export jQuery object as default.
Then use it in your script:
// script.js
import $ from "./jquery.module.js";
$(function(){
$('body').text('youpi!');
});
Do not forget to load it as a module in your document:
<script type='module' src='./script.js'></script>
http://plnkr.co/edit/a59ETj3Yo2PJ0Aqkxbeu?p=preview

Import the entire JQuery's contents in the Global scope. This inserts $ into the current scope, containing all the exported bindings from the JQuery.
import * as $ from 'jquery';
Now the $ belongs to the window object.

If it helps anyone, javascript import statements are hoisted. Thus, if a library has a dependency (eg bootstrap) on jquery in the global namespace (window), this will NOT work:
import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
import 'bootstrap/dist/js/bootstrap.min';
This is because the import of bootstrap is hoisted and evaluated before jQuery is attached to window.
One way to get around this is to not import jQuery directly, but instead import a module which itself imports jQuery AND attaches it to the window.
import jQuery from './util/leaked-jquery';
import 'bootstrap/dist/js/bootstrap.min';
where leaked-jquery looks like
import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
export default $;
export { jQuery };
EG, https://github.com/craigmichaelmartin/weather-app--birch/blob/4d9f3b03719e0a2ea3fb5ddbbfc453a10e9843c6/javascript/util/leak_jquery.js

The accepted answer did not work for me
note : using rollup js dont know if this answer belongs here
after
npm i --save jquery
in custom.js
import {$, jQuery} from 'jquery';
or
import {jQuery as $} from 'jquery';
i was getting error :
Module ...node_modules/jquery/dist/jquery.js does not export jQuery
or
Module ...node_modules/jquery/dist/jquery.js does not export $
rollup.config.js
export default {
entry: 'source/custom',
dest: 'dist/custom.min.js',
plugins: [
inject({
include: '**/*.js',
exclude: 'node_modules/**',
jQuery: 'jquery',
// $: 'jquery'
}),
nodeResolve({
jsnext: true,
}),
babel(),
// uglify({}, minify),
],
external: [],
format: 'iife', //'cjs'
moduleName: 'mycustom',
};
instead of rollup inject, tried
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
// 'node_modules/jquery/dist/jquery.js': [ '$' ]
// 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};
package.json
"devDependencies": {
"babel-cli": "^6.10.1",
"babel-core": "^6.10.4",
"babel-eslint": "6.1.0",
"babel-loader": "^6.2.4",
"babel-plugin-external-helpers": "6.18.0",
"babel-preset-es2015": "^6.9.0",
"babel-register": "6.9.0",
"eslint": "2.12.0",
"eslint-config-airbnb-base": "3.0.1",
"eslint-plugin-import": "1.8.1",
"rollup": "0.33.0",
"rollup-plugin-babel": "2.6.1",
"rollup-plugin-commonjs": "3.1.0",
"rollup-plugin-inject": "^2.0.0",
"rollup-plugin-node-resolve": "2.0.0",
"rollup-plugin-uglify": "1.0.1",
"uglify-js": "2.7.0"
},
"scripts": {
"build": "rollup -c",
},
This worked :
removed the rollup inject and commonjs plugins
import * as jQuery from 'jquery';
then in custom.js
$(function () {
console.log('Hello jQuery');
});

webpack users, add the below to your plugins array.
let plugins = [
// expose $ and jQuery to global scope.
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
];

I did not see this exact syntax posted yet, and it worked for me in an ES6/Webpack environment:
import $ from "jquery";
Taken directly from jQuery's NPM page. Hope this helps someone.

If you are not using any JS build tools/NPM, then you can directly include Jquery as:
import 'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;
You may skip import(Line 1) if you already included jquery using script tag under head.

import {jQuery as $} from 'jquery';

My project stack is: ParcelJS + WordPress
WordPress got jQuery v1.12.4 itself and I have also import jQuery v3^ as module for other depending modules as well as bootstrap/js/dist/collapse, for example... Unfortunately, I can’t leave only one jQuery version due to other WordPress modular dependencies.
And ofcourse there is conflict arises between two jquery version. Also keep in mind we got two modes for this project running Wordpress(Apache) / ParcelJS (NodeJS), witch make everything little bit difficulty. So at solution for this conflict was searching, sometimes the project broke on the left, sometimes on the right side.
SO... My finall solution (I hope it so...) is:
import $ from 'jquery'
import 'popper.js'
import 'bootstrap/js/dist/collapse'
import 'bootstrap/js/dist/dropdown'
import 'signalr'
if (typeof window.$ === 'undefined') {
window.$ = window.jQ = $.noConflict(true);
}
if (process) {
if (typeof window.jQuery === 'undefined') {
window.$ = window.jQuery = $.noConflict(true);
}
}
jQ('#some-id').do('something...')
/* Other app code continuous below.......... */
I still didn’t understand how myself, but this method works. Errors and conflicts of two jQuery version no longer arise

Pika is a CDN that takes care of providing module versions of popular packages
<script type='module'>
import * as $ from 'https://cdn.skypack.dev/jquery';
// use it!
$('#myDev').on('click', alert);
</script>
Skypack is Pika, so you could also use: import * as $ from 'https://cdn.pika.dev/jquery#^3.5.1';

import $ from 'jquery'
// export for others scripts to use
window.$ = window.jQuery = $

First of all, install and save them in package.json:
npm i --save jquery
npm i --save jquery-ui-dist
Secondly, add a alias in webpack configuration:
resolve: {
root: [
path.resolve(__dirname, '../node_modules'),
path.resolve(__dirname, '../src'),
],
alias: {
'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
},
extensions: ['', '.js', '.json'],
}
It work for me with the last jquery(3.2.1) and jquery-ui(1.12.1).
See my blog for detail: http://code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html

Import jquery (I installed with 'npm install jquery#1.9.1')
import 'jquery/jquery.js';
Put all your code that depends on jquery inside this method
+function ($) {
// your code
}(window.jQuery);
or declare variable $ after import
var $ = window.$

I wanted to use the alread-buildy jQuery (from jquery.org) and all the solutions mentioned here didn't work, how I fixed this issue was adding the following lines which should make it work on nearly every environment:
export default ( typeof module === 'object' && module.exports && typeof module.exports.noConflict === 'function' )
? module.exports.noConflict(true)
: ( typeof window !== 'undefined' ? window : this ).jQuery.noConflict(true)

You can import like this
import("jquery").then((jQuery) => {
window.$ = jQuery;
window.jQuery = jQuery;
import("bootstrap").then((_bs)=>{
$(function() {});
})
});

If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:
new webpack.ProvidePlugin({
'window.jQuery': 'jquery'
});
The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.

Related

Bootstrap tooltip is not a function, Popper not working

I'm trying to use separate modules of bootstrap in my website instead of include the whole minified file. But I'm freaking out, why is that so complicated? Or I'm complicating this?
"devDependencies": {
"exports-loader": "1.1.1",
"webpack": "4.39.2",
"uglify-js": "3.6.0",
},
"dependencies": {
"bootstrap": "4.3.1",
"jquery": "3.4.1",
"popper.js": "1.14.7",
}
custom bootstrap.js in /js
/* Tries:
import $ from 'jquery';
import 'popper.js';
import 'popper.js/dist/umd/popper.js';
import 'popper.js/dist/umd/popper.min.js';
import 'bootstrap/dist/js/bootstrap.min.js'; */
window.jQuery = $;
window.$ = $;
global.$ = $;
/* BOOTSTRAP CUSTOM IMPORTS */
import 'bootstrap/js/dist/util';
import 'bootstrap/js/dist/alert';
import 'bootstrap/js/dist/button';
import 'bootstrap/js/dist/collapse';
import 'bootstrap/js/dist/dropdown';
import 'bootstrap/js/dist/modal';
import 'bootstrap/js/dist/tooltip';
import 'bootstrap/js/dist/popover';
import 'bootstrap/js/dist/tab';
With that, my code compile with success but on chrome console this error appear
Uncaught TypeError: $(...).tooltip is not a function
If I include this on my webpack.config.js:
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
'window.jQuery': 'jquery/src/jquery',
Popper: ['popper.js', 'default'],
}),
The tooltip error is gone, but starts to do error on other libs, like:
//Error on chrome console
Uncaught TypeError: $(...).mask is not a function
My Loading order of JS is:
LIBS (A WEBPACK MERGED FILE WITH ALL OTHER LIBS, LIKE JQUERY, MASKS, SLICK...)
BOOTSTRAP
POLYFILL
Searching the internet I see that a lot of people are experiencing this problem but the solutions they present are not working for me.
Please, anybody can help me?
Thanks for responses.
I figured out what is going on, not really understanding why but, bootstrap imports with JQuery were causing conflicts in the use of jquery by plugins, so, I had to remove jquery imported from bootstrap file then include manually on another process of plugins file, like that:
/* BOOTSTRAP.js CUSTOM IMPORTS */
//removed jquery imports
import 'bootstrap/js/dist/util';
import 'bootstrap/js/dist/alert';
import 'bootstrap/js/dist/button';
...
webpack.config:
//I had to maintain that provider
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
Popper: ['popper.js', 'default'],
}),
new MergeIntoSingleFilePlugin({
files: {
"js/libs.base.js": [
//included jquery min file on merge of plugins
path.join(source, 'src/libs/jquery', 'jquery-3.4.1.min.js'),
path.join(source, 'src/libs/jquery-mask', 'jquery.mask.min.js'),
...
I think this can help.
// TOOLTIP PLUGIN DEFINITION
// =========================
var old = $.fn.tooltip
$.fn.tooltip = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})

How to make an import shortcut/alias in create-react-app?

How to set import shortcuts/aliases in create-react-app?
From this:
import { Layout } from '../../Components/Layout'
to this:
import { Layout } from '#Components/Layout'
I have a webpack 4.42.0 version.
I don't have a webpack.config.js file in the root directory. I've tried to create one myself with this code inside:
const path = require('path')
module.exports = {
resolve: {
alias: {
'#': path.resolve(__dirname, 'src/'),
}
}
};
But it doesn't seem to work. I've seen the NODE_PATH=. variant in .env file. But I believe, it is deprecated - better not to use. And also, I have a posstcss.config.js file. Because I've installed the TailwindCss and I import the CSS library there. I've tried to paste the same code there, but it also didn't work.
It is finally possible with Create React App v.3
Just put:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
into jsconfig.json or tsconfig.json if you use Typescript
Here is wonderful article about this.
Simplest way to archive this follow below steps. (same way as #DennisVash showed as but in simple form)
Installation - install and setup CRACO.
yarn add #craco/craco
# OR
npm install #craco/craco --save
Create a craco.config.js file in the root directory and configure CRACO:
/* craco.config.js */
const path = require(`path`);
module.exports = {
webpack: {
alias: {
'#': path.resolve(__dirname, 'src/'),
'#Components': path.resolve(__dirname, 'src/components'),
'#So_on': path.resolve(__dirname, 'src/so_on'),
}
},
};
Update the existing calls to react-scripts in the scripts section of your package.json file to use the craco CLI:
/* package.json */
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
}
Done! Setup is completed.
Now let's test it.
// Before
import Button from "./form/Button"
import { Layout } from '../../Components/Layout'
// After
import Button from "#/form/Button"
import { Layout } from '#Components/Layout'
Documentation Craco
Thank you. :)
// Absolute path: paths which are relative to a specific path
import Input from 'components' // src/components
import UsersUtils from 'page/users/utils' // src/page/users/utils
// Alias path: other naming to specific path
import Input from '#components' // src/components
import UsersUtils from '#userUtils' // src/page/users/utils
In order for webpack's aliases to work, you need to configure the default webpack.config.js of create-react-app.
The official way is to use the eject script.
But the recommended way is to use a library without ejecting (find the most modern library for that).
VSCode IntelliSense
In addition, you should add jsconfig.json file for path IntelliSense in VSCode (or tsconfig.json), see followup question.
Now such code with IntelliSense will work:
// NOTE THAT THOSE ARE ALIASES, NOT ABSOLUTE PATHS
// AutoComplete and redirection works
import {ColorBox} from '#atoms';
import {RECOIL_STATE} from '#state';
If you want to use:
// this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of this:
import MyUtilFn from '../../../../utils/MyUtilFn';
use the node module plugin for resolving the urls https://www.npmjs.com/package/babel-plugin-module-resolver. By installing it and adding it to your webpack/babel.rc file.
Step 1
yarn add --dev babel-plugin-module-resolver
add this plugin
Step 2
in babel.config.js file
ALIAS NAME ALIAS PATH
#navigation ./src/navigation
#components ./src/components
#assets ./assets
[
"module-resolver",
{
root: ["./src"],
alias: {
"^~(.+)": "./src/\\1",
},
extensions: [
".ios.js",
".android.js",
".js",
".jsx",
".json",
".tsx",
".ts",
".native.js",
],
},
];
Step 3
import example
import SomeComponent from '#components/SomeComponent.js';
Step 4
restart server
yarn start
Reference link: How to use import aliases with React native and VSCode

Bootstrap 4 Beta importing Popper.js with Webpack 3.x throws Popper is not a constructor

So Bootstrap 4 Beta is out... yey! However Tether has been replaced by Popper.js for tooltip (and other features). I saw an error thrown in the console fast enough to advise me of the change to Popper.js:
Bootstrap dropdown require Popper.js
Seems easy enough, I went and updated my webpack.config.js (the entire config can be seen here) and Bootstrap then started working (the only change I did was to replace Tether with Popper):
plugins: [
new ProvidePlugin({
'Promise': 'bluebird',
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
Popper: 'popper.js'
}),
I also did the import 'bootstrap' in my main.ts file.
However I now have another problem (which I did not have with Tether), a new error is thrown in the console:
Uncaught TypeError: Popper is not a constructor
If I try to debug in Chrome, I do have Popper loaded as an Object (which is why Bootstrap stopped complaining) as you can see in the print screen below.
Finally to include all my code. I use Bootstrap tooltip with a simple custom element built with Aurelia and TypeScript (which used to work with previous Bootstrap alpha 6 and Tether)
import {inject, customAttribute} from 'aurelia-framework';
import * as $ from 'jquery';
#customAttribute('bootstrap-tooltip')
#inject(Element)
export class BootstrapTooltip {
element: HTMLElement;
constructor(element: HTMLElement) {
this.element = element;
}
bind() {
$(this.element).tooltip();
}
unbind() {
$(this.element).tooltip('dispose');
}
}
Looks like I did not import Popper correctly, if so then what is the best way to achieve that with Webpack 3.x?
While browsing Bootstrap 4 documentation. I actually found a section about Webpack which explains how to install it correctly. Following the Bootstrap - installing with Webpack documentation, the answer is to simply modify the webpack.config.js with the following:
plugins: [
// ...
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
})
// ...
]
and let's not forget to import it in the main.ts
import 'bootstrap';
and voilà! We are back in business :)
If you are using Webpack Do this:
window.$ = window.jQuery = require('jquery');
window.Popper = require('popper.js').default; // pay attention to "default"
require('bootstrap/dist/js/bootstrap');
In bootstrap": "^4.1.1" no need to import jquery and popper.js because those plugins will be already included when 'bootstrap' or bootstrap's plugins imported individually.
Notice that if you chose to import plugins individually, you must also
install exports-loader
No need to require files require('exports-loader?file ... '); as mentioned here because this will be taken care automatically by just installing $ npm install exports-loader --save-dev
import 'bootstrap'; // Import all plugins at once
//
// Or, import plugins individually
//
// import 'bootstrap/js/src/alert';
// import 'bootstrap/js/src/button';
// import 'bootstrap/js/src/carousel';
// import 'bootstrap/js/src/collapse';
// import 'bootstrap/js/src/dropdown';
// import 'bootstrap/js/src/modal';
// import 'bootstrap/js/src/popover';
// import 'bootstrap/js/src/scrollspy';
// import 'bootstrap/js/src/tab';
// import 'bootstrap/js/src/tooltip';
// import 'bootstrap/js/src/util';
There is no need to do anything like below:
const webpack = require('webpack');
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
})
]
}
}
I am a vue.js developer and in new vue-cli-3, we create vue.config.js in root and place code like above to register new plugin, but as said there is no need to do all this in bootstrap": "^4.1.1".
Bootstrap's tooltip plugin is depend on popper.js and need to be enabled manually, so you can do like below in the component where you use tooltip element:
<script>
import $ from 'jquery';
export default {
mounted() {
$('[data-toggle="tooltip"]').tooltip();
},
};
</script>
I just ran into the same issue, and the solution is described here: https://github.com/FezVrasta/popper.js/issues/287
My main.ts now looks like something like the following:
import "jquery";
import Popper from "popper.js";
(<any>window).Popper = Popper;
require("bootstrap");
And I had to run npm install #types/requirejs --save to get the call to require working.
EDIT: I totally missed this the first time around, but the documention actually has a better way to solve this https://getbootstrap.com/docs/4.0/getting-started/webpack/
plugins: [
...
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default'],
// In case you imported plugins individually, you must also require them here:
Util: "exports-loader?Util!bootstrap/js/dist/util",
Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
...
})
...
]
In ASP.net Core 2 project add the following scripts to of main HTML file ("_Layout.cshtml" file)
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/js/popper.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
For me it's working.

Adding Colorbox to my ReactJS application creates "jQuery is not defined"

I'm trying to add Colorbox library to my project created with create-react-app. I've installed jquery-colorbox package via npm and added imports in one of my *.js files:
import $ from 'jquery'; // also tried: import jQuery from 'jquery';
import 'jquery-colorbox';
After that, all I'm getting is an error:
ReferenceError: jQuery is not defined
(anonymous function)
node_modules/jquery-colorbox/jquery.colorbox.js:1105
1102 |
1103 | publicMethod.settings = defaults;
1104 |
> 1105 | }(jQuery, document, window));
1106 |
1107 |
1108 |
Anyone have any suggestions how to manage with that problem?
Also, the code I want to run with the Colorbox library is something like this:
$(function() {
$('.colorbox-group' + id).colorbox({
rel: 'colorbox-group' + id,
maxWidth: '95%',
maxHeight: '95%'
});
});
UPDATE #1
Also... tried with CDN's and added these lines to index.html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js"></script>
And run code inside one of JS files of my app: $.colorbox('something');.
Result:
TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery___default.a.colorbox is not a function
Solution 1: Using cdn for jquery & jquery-colorbox
Here is a simple github repository, I have made using reactjs. Hope it helps!
Solution 2: Using npm packages for jquery & jquery-colorbox
Here is a github repository using npm packages with react setup. I have also had the same issue that you got for 'jQuery' undefined. The solution is in webpack config by adding a webpack plugin for jQuery. Add this in your webpack-config file:
On top first import the webpack:
let webpack = require('webpack');
and then add this code:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
Solution 3: specifically for 'create-react-app'
Update the import in your app.js file like below:
import jQuery from 'jquery';
window.jQuery = jQuery;
require('jquery-colorbox');
Hope it solves your query.
It looks like it is using the variable jQuery rather than $. I might try importing the jQuery object by its name, for example:
import {$, jQuery} from 'jquery';
or maybe just:
import jQuery from 'jquery';

order dependencies: jQuery is not defined with browserify

I am trying to use a plugin that is in /js/lib/stellar.jquery.js:
var $ = require('jquery');
require('./lib/stellar.jquery')
$(function(){
$.stellar();
});
When I run this though I get jQuery is not defined. I think the stellar jQuery plugin is loading before the jq library. At the bottom of the stellar plugin there's this code:
...
// Expose the plugin class so it can be modified
window.Stellar = Plugin;
}(jQuery, this, document));
Changing "jQuery" to "$" does not work either, gives "$ is not defined"
There is not any need to specify order for dependencies.
Because neither jQuery nor your plugin support CommonJS modules, you need to shim them to make them compatible with the browserify modules concept.
npm install browserify-shim --save-dev
add alias for jQuery and your plugin to your package.json (optional, but recommended)
"browser":{
"customPlugin": "path/to/custom/plugin",
"jquery": "./node_modules/jquery/dist/jquery.js"
}
add browserify shim transformation to enable shimming by adding to your package.json
"browserify": {
"transform": [
"browserify-shim"
]
}
configure shims
"browserify-shim": {
"jquery" : "jQuery",
"customPlugin" : { "depends": [ "jquery:jQuery" ] },
}
Consider, in dependencies configuration before colon you should specify file name, NOT SHIMMED MODULE NAME!!!
after colon you should specify identifier, which is expected by your module in global namespace.
Then, require your plugin to initialize it's code before usage
'use strict';
require('customPlugin');
var $ = require('jQuery');
$('.some-class-selector').myCustomPlugin();
Seems like another solution is to add :
global.jQuery = require("jquery")

Categories

Resources