npmwebpacklaravel-mixjs-cookie

How to correctly require js-cookie with npm and webpack? Uncaught ReferenceError


Strange problem but I'm sure it's easily solved. I've tested on a completely empty webpack project.

It says npm js-cookie has 0 dependencies so I guess this should work on its own.

$ npm install js-cookie --save

Then simply ran this in my script file.

require('js-cookie');

Cookies.set('name', 'value');

The node vendor js-cookie 100% exists and no errors on the require.

However just get this error.

enter image description here


Heres a test project you can download and spin up using npm install and then npm run production to see error.

http://dev.joshmoto.wtf/npm-webpack-jscookie-project.zip

I'm using laravel mix but I don't see how that can be a the problem?


Solution

  • You have to assign the required module to a variable in order to use it.

    const Cookies = require('js-cookie'); //assign module to variable called "Cookies"
    Cookies.set('name', 'value');
    console.log(Cookies.get('name'));
    

    Read more about this here: https://nodejs.org/api/modules.html