如何通过npm/webpack正确引入Gridstack v1.1?
Hey there! Let's get your Gridstack v1.1 setup working with webpack properly. Here's what you need to know:
1. Required Dependencies for Gridstack v1.1
Gridstack v1.x is built as a jQuery plugin, so it relies on two key dependencies that aren't included in the gridstack npm package itself:
jquery(v3.x is recommended and fully compatible with v1.1)jquery-ui(specifically thesortableanddraggablewidgets, which Gridstack uses for drag-and-drop functionality)
First, install these missing dependencies:
npm install jquery jquery-ui --save
2. Correct Import & Initialization Code
Your current import approach won't work because Gridstack v1.1 doesn't export a standalone Gridstack class with an init() method—it attaches itself to the global jQuery object instead. Here's how to fix your Main.js:
// 1. Import jQuery first import $ from 'jquery'; // 2. Import the required jQuery UI widgets (Gridstack depends on these) import 'jquery-ui/ui/widgets/sortable'; import 'jquery-ui/ui/widgets/draggable'; // 3. Import Gridstack's JS and core CSS files import 'gridstack/dist/gridstack.js'; import 'gridstack/dist/gridstack.css'; // Optional: Import extra styles if you need gridstack-extra features import 'gridstack/dist/gridstack-extra.css'; // 4. Initialize Gridstack using the jQuery plugin syntax $(document).ready(function() { // Ensure you have a .grid-stack element in your HTML markup const grid = $('.grid-stack').gridstack({ // Add your configuration options here, e.g.: // width: 12, // cellHeight: 80 }).data('gridstack'); console.log(grid); // This should now log the valid Gridstack instance });
3. Webpack Configuration Tweak
To make sure Gridstack can access the global jQuery object (which it expects), add the ProvidePlugin to your webpack config. This makes $ and jQuery available globally across your project:
In webpack.config.js:
const webpack = require('webpack'); module.exports = { // ... your existing webpack configuration plugins: [ // Add this plugin to expose jQuery globally new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }) ] };
Why Your Original Code Failed
The error TypeError: ...init is not a function occurs because Gridstack v1.1 doesn't expose an ES module export with an init() method. Unlike newer Gridstack versions (v2+), v1.x is strictly a jQuery plugin—so you have to initialize it via the jQuery .gridstack() method, not a standalone class.
内容的提问来源于stack exchange,提问作者Karakayn

