Incorporate fullcalendar into your webpack project for seamless integration

While utilizing npm, webpack, and FullCalendar, I encountered an error in the browser console when working with fullcalendar:

main.js:37556 Uncaught TypeError: (0 , _jquery2.default)(...).fullCalendar is not a function

Any ideas on how to resolve this issue?

The versions I am using are FullCalendar 3.0.0-beta and jQuery 3.1.0. Below is a snippet of my code.

index.js:

import $ from 'jquery'
import jQueryUI from 'jquery-ui'
import moment from 'moment'
import fullCalendar from 'fullcalendar'


$('#timetable').fullCalendar({
    editable: true,
    firstDay: 1,
    droppable: true,
})

webpack.config.js:

var path = require("path")
var webpack = require("webpack")
var BundleTracker = require("webpack-bundle-tracker")

module.exports = {
    context: __dirname,
    entry: [
        'fullcalendar',
        './static/index',
    ],
    output: {
        path: path.resolve('./static/bundles/'),
        filename: "[name].js",
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
    ],

    resolve: {
        modulesDirectories: ['node_modules'],
        extensions: ['', '.js'],
    },

    module: {
        loaders:[
            { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015'] } }
        ]
    }

}

Answer №1

Even though I may be a bit tardy to the celebration, I still wanted to share my insights in case someone stumbles upon this post via Google.

When dealing with a jQuery Plugin like FullCalendar through Webpack, it's essential to ensure that jQuery is accessible in the global namespace before the plugin can be utilized through require/import.

This is how I set up my webpack.config.js:

var webpack = require("webpack")
var path = require("path")
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
    entry: {
        app: "./index.js",
        vendor: [
            "jquery",
            "moment",
            "fullcalendar"
        ]
    },
    output: {
        path: path.join(__dirname, '../../public'),
        publicPath: '/',
        filename: "scripts/app.[chunkhash].js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: ExtractTextPlugin.extract("style", ["css"]) },
            { test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery' },
            { test: require.resolve('moment'), loader: 'expose?moment' }
        ]
    },
    resolve: {
      alias: {
        jquery: path.resolve(path.join(__dirname, '../..', 'node_modules', 'jquery')),
        fullcalendar: 'fullcalendar/dist/fullcalendar'
      }
    },
    plugins: [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.CommonsChunkPlugin({ names: ["vendor"], filename: "scripts/[name].[chunkhash].js" }),
        new ExtractTextPlugin("styles/[name].[chunkhash].css"),
        new HtmlWebpackPlugin({
            template: "index.html.handlebars"
        }),
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) 
    ]
};

The crucial part is where jQuery and moment are exposed to the global namespace using the loader: 'expose?$!expose?jQuery' syntax.

Additionally, since FullCalendar packaging doesn't automatically integrate with the require function, I created an alias for easier usage:

alias: { fullcalendar: 'fullcalendar/dist/fullcalendar' }
.

With these setups, loading FullCalendar via require/import becomes seamless and straightforward.

As for styles, no aliases were established yet, so a relative reference to the CSS file was implemented:

@import "../../../node_modules/fullcalendar/dist/fullcalendar.css";

You also have the option to substitute fullcalendar.js with fullcalendar.min.js to skip re-compression. However, bundling all vendor JS files together might lead to better compression results. (Same applies to CSS files - fullcalendar.css with fullcalendar.min.css)

Disclaimer: While I'm not certain if this method is deemed as the "correct" approach, after some trial and error with webpack, this setup proved to make working with jQuery plugins such as FullCalendar and Select2 more manageable.

For further reference, links to relevant files in a public repository that follow this pattern:

webpack.config.js: https://github.com/thegrandpoobah/mftk-back-office/blob/e531de0a94130d6e9634ba5ab547a3e4d41c5c5f/app/src/public/webpack.config.js

Style SCSS: https://github.com/thegrandpoobah/mftk-back-office/blob/e531de0a94130d6e9634ba5ab547a3e4d41c5c5f/app/src/public/styles/main.scss

Module utilizing FullCalendar: https://github.com/thegrandpoobah/mftk-back-office/blob/e531de0a94130d6e9634ba5ab547a3e4d41c5c5f/app/src/public/students/index.js#L277

Answer №2

Here is a detailed guide on how to set up your project using information from various sources. Start by ensuring that you have moment.js properly installed:

npm install moment

Next, make sure you have the fullcalendar version 3.10.2 installed, which is the latest in the version 3 series. This version is optimized to not bundle jQuery or moment.js. Even though it's not the most recent version, it uses the old syntax to maintain compatibility with legacy code:

npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aaccdfc6c6c9cbc6cfc4cecbd8ea99849b9a8498">[email protected]</a>

Then, proceed to install script-loader:

npm install --save-dev script-loader

If you are working with Laravel, add the following lines below bootstrap and jquery in resources/js/bootstrap.js (note the use of script-loader):

window.moment = require('moment');
require('script-loader!fullcalendar/dist/fullcalendar');
require('script-loader!fullcalendar/dist/locale-all');

Include the CSS styles in resources/sass/app.scss:

@import '~fullcalendar/dist/fullcalendar.min.css';

Finally, run the development build command:

npm run dev

For production, use:

npm run prod

And that's all there is to it!

Answer №3

I have discovered a simpler solution that worked for us.

In our project, we were using fullcalendar along with scheduler and transitioning from Rails sprockets to webpack. When we added fullcalendar to a lazyloaded chunk in webpack, it unexpectedly brought in two extra versions of moments and jquerys (yes, two), overriding our configuration changes made in the original version located in our vendor file.

Our goal was to include fullcalendar without any module processing, which turned out to be unnecessary anyway. Thankfully, webpack's script-loader came in handy for this task.

require('script-loader!fullcalendar/dist/fullcalendar.js')

Once you add this line, fullcalendar is included as desired, free from any additional processing. The same can be applied to the scheduler plugin for jquery.

Answer №4

To resolve the issue with webpack 5, you can use the following code:

module: {
        rules: [
            {
                test: require.resolve('jquery'),
                    loader: 'expose-loader',
                    options:  { 
                        exposes: ["$", "jQuery"]
                    }
            },
            {
                test: require.resolve('moment'),
                    loader: 'expose-loader',
                    options:  { 
                        exposes: "moment"
                    }
            },
            {
                test: require.resolve('fullcalendar'),
                use: [
                    {
                      loader: 'script-loader',
                      options: 'fullcalendar/dist/fullcalendar.js'
                    }
                  ]
            },
            {
                test: require.resolve('fullcalendar-scheduler'),
                use: [
                    {
                      loader: 'script-loader',
                      options: 'fullcalendar/dist/fullcalendar-scheduler.js'
                    }
                  ]
            },
        ]
    },

Answer №5

I decided to implement fullCalendar in this scenario:

$("#fullcalendar-activities").fullCalendar({
        header: {
         left: 'prev,next today',
         center: 'title',
         right: 'month,basicWeek,basicDay'
        },
        events: events,
        defaultView: 'month'
 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error occurred when trying to initialize the module dx: [$injector:modulerr]. This was due to a bad directive name, 'DOMComponent', which is invalid

Encountering an issue while running the application with the following versions: Angular: 1.6.8 JQuery: 2.2.4 Bower: 1.8.2 The screen is showing up blank. An error has been thrown: [$injector:modulerr] Failed to instantiate module ftfwebApp due to: E ...

Populate DataTable with HTML content by fetching it through Ajax requests

My goal is to dynamically load the HTML returned from a controller into a div when a user clicks on a row in a table. Check out my code snippet below: // Add event listener for opening and closing details jQuery('#exRowTable tbody').on ...

Converting JSEncrypt for PHP Asymmetric Encryption

I am attempting to establish Asymmetric encryption between a client and server, where the client possesses the public key and the server holds the private key. On the client side, I am using JSEncrypt in JavaScript to encrypt data with my public key. I th ...

Having Trouble Running Ionic on My Windows 7 System

I've been following the steps in the "Getting Started with Ionic" guide, but I'm stuck at step 2 "Start a Project". Whenever I try to create an Ionic project, I encounter an error. Here's what I get: C:\Users\username>ionic sta ...

What is the best way to access a JSON file using Javascript or JQuery?

If I have a JSON Object like this: {"success":true, "uploaded_url":uploaded_url} What is the best way to alert("uploaded_url") from it? ...

What is the solution for validating requests in Node.js?

I am currently facing an issue with my controller that is meant to validate data before saving it into the database. Despite setting up validation checks, I am experiencing crashes when testing on Postman. Whenever I deliberately leave some data empty an ...

Leveraging NodeJS to operate an Angular 2 application with real-time repackaging functionality

Issue Overview In the past, I had my NodeJS application running on port :3000, while my Angular2 app was served by ng serve on port :4200. They communicated successfully with each other using WebPack. Now, I have switched to building the Angular2 app usi ...

Error: The property 'send' cannot be read because it is undefined - Node.js

We have integrated a Node.js package called springedge to handle SMS functionality in our project: npm install springedge Below is the code snippet from the file send_messages.js: var springedge = require('springedge'); var params = { &apos ...

Oops! Looks like there's a type error in module "*.mdx" - it seems that it doesn't have the exported member "metadata". Maybe try using "import metadata from "*.mdx"" instead?

I am attempting to extract metadata from an mdx file. I have followed the guidelines outlined in NextJS Markdown Frontmatter, but encountered build errors. It is important to note that I am unable to utilize fs. Code Section Page.tsx File import Conte ...

Saving Backbone.js Collection as Text File on HDD & Re-importing Data

After experimenting with Backbone.js for a while, I've relied on localStorage to store most of my app data. However, I now want to explore the possibility of exporting my collection to plain text for easy backup purposes. Essentially, I envision a fea ...

Webpack: The bootstrap-loader is experiencing difficulty locating the installed bootstrap 4 module

Hello, I am currently facing an issue while attempting to integrate Bootstrap 4 into our webpack configuration. I am encountering difficulties with the bootstrap-loader as it seems to be unable to locate the installed Bootstrap 4 node module. Could the pro ...

Demonstrating the process of sending a list of items from Angular to an Express API connected to MongoDB

I am currently working on developing an Express Mongo API that is being utilized by an Angular application. My query revolves around posting a list of items. Here is my MongoDB schema: var TestSchema = new mongoose.Schema({ title: String, colors: ...

Testing React components with Jasmine

I need some guidance on how to properly integrate the Jasmine test runner into my React app without using Karma. Currently, I am deploying my test cases to a TV and running the standalone spec runner on the set. To do this, I had to inline and transpile th ...

Preventing Woocommerce from redirecting when the apply discount button is clicked during checkout using jQuery

When I manually click the "apply discount" button on the checkout page, it applies the discount and stays on the checkout page. However, if I click the "apply discount" button with jQuery on the checkout page, it applies the discount but redirects me to th ...

Encountered a TypeError: The super expression should be defined as null or a function, not undefined in a React application

Contents of package.json { "name": "react_playlist", "version": "1.0.0", "description": "All course files for the React tutorial playlist on YouTube by Net Ninja", "main": "index.js", "scripts": { "test": "echo \"Error: no test specifie ...

Issue with Three.js: The mouse hover effect does not revert back to the previous color

Currently, I am working on creating a pattern using Three.js. The goal is to change the color of a face to gray when the user hovers over it with the mouse, and then revert it back to its original light blue color when the mouse moves away. Unfortunately, ...

Troubleshooting problems with dynamic elements and qTip

On my page, I have an UpdatePanel where new forms are added when clicked. These new elements contain images that need to utilize qTip. This is the current setup: $(document).ready(function () { $('.ttip').qtip({ conten ...

JSX parsing is not supported by Webpack

Recently, I started delving into webpack and react. While troubleshooting a particular issue, I noticed that the solutions I came across didn't quite fit my scenario; they were mainly related to missing dependencies or incorrect webpack config file fo ...

Using AngularJS to iterate over items in a list and display tag attributes

Can someone help me understand how to utilize item from ng-repeat within the same tag where I am declaring ng-repeat? In a hypothetical template language, this is what I want: {% for item in items %} <li data-theme="{{ item.dataTheme }}">{{ it ...

Implementing a Global Timezone Setting for the Entire Application

Currently, I am focusing on Timezone settings within my application. My goal is to adjust the default timezone that the browser automatically selects when... let date = new Date() The function provides the date and time based on the browser's timezon ...