2

I have a React Redux application. Im adding materialize as the CSS framework, but materialize requires jquery. So i installed Jquery and added it to my project via npm. If i import jquery like so

import $ from 'jquery';

No errors are thrown and im able to use it. But only on that component. So i added the wepback plug so i can call $ anymore in my react application. However, when i do this as described on webpacks website, it get the following error.

Line 13:  '$' is not defined 

Any ideas on why this is ?

app.js

import React  from 'react';
import '../styles/index.css';
import Header from './header/Header';

class App extends React.Component {
    constructor(props){
        super(props);
        console.log('Application ready');
    }
    componentWillMount(){
        $('ul.tabs').tabs();
    }
    render = () => (
        <div>
            <Header />
            <div>
                {this.props.children}
            </div>
        </div>
    )
}
export default App;

webpack.config.dev.js

    alias: {

  // Support React Native Web
  // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  'react-native': 'react-native-web',
  jquery: "jquery/src/jquery" // What i added 
  // $: "jquery/src/jquery" 
},

jquery is in the node_modules folder, from the npm install, i didnt add it to any other location.

AJ_
  • 3,787
  • 10
  • 47
  • 82
  • you should use material-ui: http://www.material-ui.com/#/ it's a material design impl for react. – Ahmed Musallam Jan 26 '18 at 18:21
  • Is related with this: https://stackoverflow.com/questions/28969861/managing-jquery-plugin-dependency-in-webpack/47333184#47333184 – JPRLCol Jan 26 '18 at 19:50

2 Answers2

12

You've aliased jQuery to the global variable jQuery, not $ - do alias: { $: 'jquery' }.

Wrong, this isn't what alias is for, see https://webpack.js.org/configuration/resolve/

Global variables in (browser) JS are really properties of window. So at the start of your script you could do

import $ from 'jquery';
window.$ = $;

and it'd be available globally after that. Including jQuery in its own <script> tag would do the same thing. But these are both un-webpack, a bit naughty, not modular. The 'correct' thing to do is import $ from 'jquery' in every file where you need it. Yeah this will be tedious if you need it in a lot of places, but it means you know where you need jQuery and where you don't, and if you removed all the components that used jQuery, jQuery would disappear as well.

Ben West
  • 4,398
  • 1
  • 16
  • 16
0

To add on for Gatsby.js you can npm i jquery and then import jquery in gatsby-browser.js.

import 'jquery/dist/jquery.min';
import 'popper.js/dist/popper.min'; // for navbar animation
import 'bootstrap/dist/js/bootstrap.min';

import $ from 'jquery'; in the relevant files will then detect $

C-Dev
  • 425
  • 1
  • 6
  • 15