Next.js: Import jQuery to next.config.js

Created on 20 Mar 2017  路  5Comments  路  Source: vercel/next.js

Hi,

Is there any way to add a new providerPlugin to the next.config.js file and make a plugin accessible from anywhere in my app.

Example: This is my next.config.js

const webpack = require('webpack');

module.exports = {
  webpack: (config, { dev }) => {

    config.plugins.push(
      new webpack.ProvidePlugin({
        '$': 'jquery',
        jQuery: 'jquery'
      })
    );

    return config
  }
}

And if I try to console.log(jQuery) from my index.js file:

import React from 'react';

module.exports = () =>
  console.log(jQuery);

I still can't access jQuery on the server side, so I get an exception:
ReferenceError: jQuery is not defined

In the end my goal is to import Foundation which has a jQuery dependency and then can't be imported properly in my app.
Thanks for the help!

Most helpful comment

Here is my workaround for loading foundation:

//next.config.js

const webpack = require('webpack')

module.exports = {
    webpack: (config, { dev }) => {
        config.plugins.push(
            new webpack.ProvidePlugin({
                '$': 'jquery',
                'jQuery': 'jquery',
            })
        )
        return config
    }
}
//index.js

import React from 'react';
import $ from 'jquery';

export default class Index extends React.Component {

    componentDidMount(){
        const foundation = require('foundation-sites');
        $(document).foundation();
    }
}

Work with next.js 2.0.0

All 5 comments

@diskokevin Try to do this with a babel plugin.

Here is my workaround for loading foundation:

//next.config.js

const webpack = require('webpack')

module.exports = {
    webpack: (config, { dev }) => {
        config.plugins.push(
            new webpack.ProvidePlugin({
                '$': 'jquery',
                'jQuery': 'jquery',
            })
        )
        return config
    }
}
//index.js

import React from 'react';
import $ from 'jquery';

export default class Index extends React.Component {

    componentDidMount(){
        const foundation = require('foundation-sites');
        $(document).foundation();
    }
}

Work with next.js 2.0.0

Since @diskothibautha's solution is pretty great, I'm gonna close this.

Thanks @diskothibautha! Amazing ;)

When trying to use @diskothibautha 's solution, I'm running into this little ordeal.

screen shot 2017-08-21 at 19 32 48

EDIT
Works with jQuery 2.2.4 not 3+

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rauchg picture rauchg  路  3Comments

sospedra picture sospedra  路  3Comments

YarivGilad picture YarivGilad  路  3Comments

renatorib picture renatorib  路  3Comments

knipferrc picture knipferrc  路  3Comments