Search code examples
javascriptreactjssummernote

React.js + Summernote, how to import JavaScript dependency libraries


I am new to React.js and I want to use a specific WYSIWYG editor - Summernote as a component.

I am using

What I tried:

As the react-summernote documentation suggests I did the following:

  1. Installed react-summernote
  2. Added following (below) to \node_modules\webpack-dev-server\client\webpack.config.js

     ...
     ...
     plugins: [
        new UglifyJSPlugin(),
        new webpack.ProvidePlugin({
           $: "jquery",
           jQuery: "jquery"
        })
     ]
    
  3. In my component (in WYSIWYG.js) I did the following

     // WYSIWYG.js 
     import React, {Component} from 'react';
    
     import ReactSummernote from 'react-summernote';
     import 'react-summernote/dist/react-summernote.css'; // import styles
    
     // Import bootstrap(v3 or v4) dependencies 
     import 'bootstrap/js/dist/modal';
     import 'bootstrap/js/dist/dropdown';
     import 'bootstrap/js/dist/tooltip';
     import 'bootstrap/dist/css/bootstrap.css';`
    

My package.json dependency

...
"dependencies": {
    "bootstrap": "^4.0.0",
    "jquery": "^3.3.1",
    "popper.js": "^1.12.9",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts": "1.1.1",
    "react-summernote": "^2.0.0"
  },

Error am getting: (in Browser)

$not defined

And nothing important in CLI. Also I tried putting import $ from "jquery"; in my component WYSIWYG.js. I tried THIS(github problem page) too. But same problem persists.

Please help, thanks.


Solution

  • Yes am using create-react-app.

    create-react-app does not expose the webpack files for you to edit unless you eject. Another way you can use to set jQuery to the window is to follow:

    import $ from 'jquery';
    import 'bootstrap/dist/css/bootstrap.css';
    // Bootstrap JS relies on a global varaible.
    // In ES6, all imports are hoisted to the top of the file
    // so if we used `import` to import Bootstrap, it would
    // execute earlier than we have assigned the global
    // variable. This is why we have to use CommonJS require()
    // here since it doesn't have the hoisting behavior.
    window.jQuery = $;
    require('bootstrap');
    

    https://github.com/kevgathuku/react-bootstrap-jquery/pull/1/files