React - '$' is not defined

11,731

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.

Share:
11,731
AJ_
Author by

AJ_

Updated on June 04, 2022

Comments

  • AJ_
    AJ_ almost 2 years

    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.