Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - '$' is not defined

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.

like image 750
AJ_ Avatar asked Sep 05 '26 05:09

AJ_


1 Answers

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.

like image 89
Ben West Avatar answered Sep 07 '26 17:09

Ben West



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!