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?

joshmoto
  • 4,472
  • 1
  • 26
  • 45
  • 3
    const Cookies = require("js-cookie") – Mike Doe Dec 08 '19 at 10:42
  • 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. – joshmoto Dec 08 '19 at 10:57

2 Answers2

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

Reolat Her
  • 84
  • 1
  • 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. – joshmoto Dec 08 '19 at 10:57
  • 2
    You can also require the module (and set it to a const variable) in every file where you need to use it. – Reolat Her Dec 08 '19 at 11:00
1

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

Using: webpack encore from Symfony 4/5

Volmarg Reiso
  • 437
  • 4
  • 11