magnificPopup is not working with webpack - javascript

I have installed magnificPopup via "npm i magnific-popup" command after that imported it in the app.js file. But in the browser console it shows (magnificPopup is not a function )
app.js
import $ from "jQuery";
window.$ = window.jQuery = $;
import "magnific-popup";
$(document).ready(function() {
$('.play-btn').magnificPopup({ type: 'video' });
});
webpack.config.js
var path = require("path");
var webpack = require('webpack');
module.exports = {
entry: {
app: "./app/assets/scripts/app.js",
vendor: "./app/assets/scripts/vendor.js"
},
output: {
path: path.resolve(__dirname, "./app/temp/scripts"),
filename: "[name].js"
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ["es2015"]
}
}
}
]
},
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery'
}),
]
}

I've fixed the problem
jQuery doesn't need to import in app.js
After fixing app.js file looks like this
import "magnific-popup";
$(document).ready(function() {
$('.play-btn').magnificPopup({ type: 'video' });
});

Its simple, your files are not on the import location. Please check your path or file location/position once. Moreover please check your JQuery library if that included then it should be above this library files/code.

Related

webpack - ReferenceError: $ is not defined

I've read many answers to this question but I can't get to resolve my issue so I come here for help...
Here's my webpack conf file :
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// https://github.com/webpack-contrib/mini-css-extract-plugin
const webpack = require('webpack');
const jquery = require('jquery');
module.exports = {
mode: 'development',
entry: './assets/js/app.js',
output: {
path: path.resolve(__dirname, 'public/dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../',
hmr: process.env.NODE_ENV === 'development',
},
},
'css-loader',
],
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 100000,
},
},
{
loader:"file-loader",
options:{
name:'[name].[ext]',
outputPath:'images/' //the images will be emited to dist/images/ folder
}
}
],
},
{
// Exposes jQuery for use outside Webpack build
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: 'jQuery'
}, {
loader: 'expose-loader',
options: '$'
}]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[name]-[id].css',
ignoreOrder: false,
}),
/* Use the ProvidePlugin constructor to inject jquery implicit globals */
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery'",
"window.$": "jquery"
})
],
/*resolve: {
alias: {
jquery: "jquery/src/jquery"
}
}*/
};
And my entry file app.js :
// Import CSS
import 'bootstrap/dist/css/bootstrap.css';
import '#fortawesome/fontawesome-free/js/all';
import '../css/style.css';
// Import JS
import $ from 'jquery';
window.$ = jQuery;
window.jQuery = jQuery;
import * as JSZip from 'jszip'; //export xlsx
import 'bootstrap';
//require('webpack-jquery-ui');
//require('webpack-jquery-ui/css');
I keep on trying different solution but still when I use jQuery in my code I get :
ReferenceError: $ is not defined
Could you please help me out ?
Look at this in your code:
import $ from 'jquery';
window.$ = jQuery;
window.jQuery = jQuery;
Think a second.
.
.
.
.
.
.
.
.
.
.
.
.
Notice you never defined jQuery. Fix it.
import $ from 'jquery';
window.$ = $;
window.jQuery = $;
One solution to add the jquery library as external. The second solution is to add jquery to the bundle.
1. External
webpack.js
externals: {   
jquery: 'jQuery'
}
plugins: [   new webpack.ProvidePlugin({      
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'    
})]
adding jquery to html
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous">
adding jquery in js
import $ from 'jquery';
const test = $('h1').text();
console.log(`from jquery: $ {test}`);
2. The second solution, adding jquery to the bundle First you need to install jquery locally.
yarn add -D jquery
adding jquery in js
import $ from 'jquery';
const test = $('h1').text();
console.log(`from jquery: $ {test}`);
This can be optimized and split using splitChunks but that's a story for another entry;)
I added an example of external jquery use
OK the mistake was stupid, app.js was called at the end of the layout and I was trying to use jQuery in the view.
So make sure that you check the order in which your broken code and the include which contains jquery is called.

Webpack dependent plugin

i am trying to add sammyjs on webpack as a plugin. But sammyjs is dependent on jquery and jquery is also present on plugin.
Here is the code
const webpack = require('webpack')
const jquery = require('jquery')
const Sammy = require('sammy')
const {resolve} = require('path')
const webpackConfig = {
entry: "./src/js/bootstrap.js",
output: {
path: resolve("dist"),
filename: "bundle.js",
publicPath: '/dist/'
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Sammy: 'Sammy'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
resolve: {
alias: {
graph: resolve(__dirname, 'src/modules/graph'),
}
},
};
module.exports = webpackConfig;
but building it. Sammyjs keeps asking for jQuery variable:
I dont just want to import it in pages because it feels like the bundle is getting bigger.
Please tell me if i am doing right. Or there is other way to attain clean and smaller bundle.

How to import jquery in webpack

I have a problem with jquery when i using it on webpack.
My code:
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
entry: {
vendor: [
'./src/main/webapp/js/vendor/jquery-3.3.1.min.js',
// './src/main/webapp/js/vendor/fs.js',
'./src/main/webapp/js/vendor/google-adsense.js',
'./src/main/webapp/js/vendor/jquery.menu-aim.min.js',
'./src/main/webapp/js/vendor/jquery.touchSwipe.min.js',
],
app: './src/main/assets/js/desktop/app.js',
mobile: './src/main/assets/js/mobile/app.js',
touch: './src/main/assets/js/touch/app.js',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: require.resolve('jquery'),
loader: 'expose-loader?jQuery!expose-loader?$'
}
],
},
plugins: [
// new CleanWebpackPlugin(['src/main/webapp/assets']),
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
}),
new UglifyJsPlugin({
test: /\.js$/,
sourceMap: process.env.NODE_ENV === "development"
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, './src/main/webapp/js')
}
};
When above code compiles , console throws this error
vendor.js:1 Uncaught ReferenceError: webpackJsonp is not defined
at vendor.js:1
And when i try to use this
externals: {
jquery: 'jQuery'
}
It throws
vendor.js:1 Uncaught ReferenceError: jQuery is not defined
at Object.231 (vendor.js:1)
at o (common.js:1)
at Object.228 (vendor.js:1)
at o (common.js:1)
at window.webpackJsonp (common.js:1)
at vendor.js:1
And i using jquery in my core js file import $ from 'jquery'.
What did i do wrong ? any help ? Thank you.
So there are few themes in your webpack.config.js, some of which conflict. Just going to list them so I can better understand what I think you are trying to achieve.
Theme 1
You have an entry called vendor that is clearly referencing a minified jQuery library you have presumably downloaded and placed in the directory specified.
Theme 2
You also have an expose-loader that is essential exposing the jquery library from its node_modules probably listed in the dependencies of your package.json.
This makes the jquery in the node_modules available as $ and jQuery in the global scope of the page where your bundle is included.
Theme 3
You also have included the ProvidePlugin with configuration for jQuery.
The ProvidePlugin is supposed to inject dependencies into the scope of your module code, meaning you do not need to have import $ from 'jquery' instead $ and jQuery will already be available in all of your modules.
Conclusion
From what I have gathered I think you're trying to bundle jQuery from the static file at ./src/main/webapp/js/vendor/jquery-3.3.1.min.js in a vendor bundle.
You are then trying to expose the libraries in the vendor bundle to the global scope (jQuery).
Then also have your application code able to import jQuery from what is made available by the vendor bundle in the global scope.
Answer
So if that is what you are doing you need to do the following things.
Firstly, check in your package.json files dependencies for jquery. If its there you want to remove it, there's no need for it if you're going to use your jquery-3.3.1.min.js file instead to provide jQuery to your application.
Secondly, change your test of the expose-loader to trigger when it sees your jquery-3.3.1.min.js file in your entries, not resolve it from the jquery dependency from your node_modules.
This regex pattern should do the trick.
{
test: /jquery.+\.js$/,
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
}
Thirdly, remove the ProvidePlugin if you're going to import the library explicitly with import $ from 'jquery' you do not need it.
Lastly, you need to tell webpack when it sees an import for jquery it can resolve this from window.jQuery in the global scope. You can do this with the externals configuration you already referenced.
externals: {
jquery: 'jQuery'
}
With all these changes you should end up with a webpack.config.js file that looks like this.
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
entry: {
vendor: [
'./src/main/webapp/js/vendor/jquery-3.3.1.min.js',
// './src/main/webapp/js/vendor/fs.js',
'./src/main/webapp/js/vendor/google-adsense.js',
'./src/main/webapp/js/vendor/jquery.menu-aim.min.js',
'./src/main/webapp/js/vendor/jquery.touchSwipe.min.js',
],
app: './src/main/assets/js/desktop/app.js',
mobile: './src/main/assets/js/mobile/app.js',
touch: './src/main/assets/js/touch/app.js',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /jquery.+\.js$/,
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
}
],
},
plugins: [
// new CleanWebpackPlugin(['src/main/webapp/assets']),
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
}),
new UglifyJsPlugin({
test: /\.js$/,
sourceMap: process.env.NODE_ENV === "development"
})
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, './src/main/webapp/js')
},
externals: {
jquery: 'jQuery'
}
};
I hope that does not just give you the answer but enough explanation as to where you were going wrong.

Trying to Bundle CSS with ExtractTextPlugin

I'm trying to bundle my CSS into one file with Webpack. I've already got it working for my scripts.but I get an error with my CSS:
Module not found: Error: Can't resolve 'circle.css' in 'C:\Projects\tag-validator-front2\src\css'.
Here's my Webpack config:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: ["./src/ts/main.js","./src/css/css.js"],
module: {
loaders: [
{
test: /\.jsx?$/,
loader: "babel-loader"
},
{
test: /\.css/,
loader: ExtractTextPlugin.extract("css")
}
]
},
plugins: [
new ExtractTextPlugin("styles.css")
],
output: {
filename: "public/bundle.js"
}
}
main.js is for my scripts and is working, but css.js isn't. Here's css.js:
"use strict";
import circleStyles from 'circle.css';
I'm only importing one right now until I get it working, but all of my CSS will be in that directory and most in sub folders.
Try to use relative import path: import './circle.css';

Wow.js with webpack and react

I try to implement wow.js using react and webpack.
I install it via npm.
npm install --save wow.js
It install perfectly. Now the problem is how to import it properly. I can't make it work keep getting undefined.
I've tried few way:
First:
import wow from 'wow.js';
But webpack can't compile it. It says the module cannot be found. Even I using complete url import wow from /node_modules/wow.js
Second:
I'm using this solution from here:
require('imports?this=>window!js/wow.js');
But I still get cannot find modules (i change the path to my node_modules).
Third:
From here:
I'm using the expose module and try to new WOW().init(); it says Wow is undefined.
I'm not using his first solution because I want my html to look simple only has bundle.js script.
I can't found any other solution. What should I do to make it work?.
Thanks!
my webpack.config.js:
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
'bootstrap-loader',
'webpack/hot/only-dev-server',
'./src/js/index.js'
],
output: {
path: __dirname + "/build",
publicPath: "/build/",
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
],
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'react-hot!babel'
},
{
test: /\.css$/,
loader: 'style!css!postcss'
},
{
test: /\.scss$/,
loader: 'style!css!postcss!sass'
},
{ test: /\.(woff2?|ttf|eot|svg|otf)$/, loader: 'url?limit=10000' },
{
test: 'path/to/your/module/wow.min.js',
loader: "expose?WOW"
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
},
postcss: [autoprefixer]
};
Alternative option without updating your wepack config.
Install WOW.js: npm install wowjs
Import in your component: import WOW from 'wowjs';
Under componentDidMount() of your component: new WOW.WOW().init();
import React, {Component} from 'react';
import WOW from 'wowjs';
class Cmp extends Component {
componentDidMount() {
new WOW.WOW().init();
}
render() {
/* code */
}
}
export default Cmp;
Do the following steps
Install exports-loader
npm i exports-loader --save-dev
Add to webpack.config.js this loader
{
test: require.resolve('wow.js/dist/wow.js'),
loader: 'exports?this.WOW'
}
add import to your app
import WOW from 'wow.js/dist/wow.js';
You can also change .call(this) to .call(window) (wow.js last line). Found this solution here https://foundation.zurb.com/forum/posts/46574-how-to-add-js-library-from-bower

Categories

Resources