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

2

5

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?

Palinode answered 8/12, 2019 at 10:40 Comment(2)
const Cookies = require("js-cookie")Christensen
Thank dude this worked but then I had to set global.Cookies = require('js-cookie'); in order for it to work in my other required js files. But i get the idea now.Palinode
O
6

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

Oracle answered 8/12, 2019 at 10:55 Comment(2)
Ah great thanks I had to set to global.Cookies = require('js-cookie'); in order for it to work in my other required js files but I see whats going on now. Cheers for node modules link i'll read up on it.Palinode
You can also require the module (and set it to a const variable) in every file where you need to use it.Oracle
C
1

This also works import * as Cookies from 'js-cookie';

Using: webpack encore from Symfony 4/5

Churinga answered 28/10, 2020 at 17:49 Comment(1)
Nice i'll give it a shot next time. ThanksPalinode

© 2022 - 2024 — McMap. All rights reserved.