I'm trying to optimize my requireJS JavaScript app with r.js. Unfortunately it stops when it rans over the function "localStorage" (the browser-builtin localStorage-function).
The error message:
ReferenceError: localStorage is not defined
The function where the error occures:
function getFromLocalStorage()
{
return localStorage.getItem('foo') ? JSON.parse(localStorage.getItem('foo')) : {};
}
How to fix this kind of error? Is is possible to use localStore within the r.js optimizer?
More information:
The build script:
({
appDir: "../",
baseUrl: "js/",
dir: "./build",
mainConfigFile: "app.js",
paths: {
jQuery: "empty:"
},
name: "app",
findNestesDependencies: true
})
Application structure:
/
---> /js (where app.js lies)
---> /app (here lies the file with the localStore-call)
---> /lib
First off, you have a typo in your code above.
I didn't want to just edit your code, but I assume that:
return localStorage.getItemfootv') ? JSON.parse(localStorage.getItem('foo')) : {};
Is supposed to be:
return localStorage.getItem('foo') ? JSON.parse(localStorage.getItem('foo')) : {};
With that change, I copied your code into a project of mine and it ran through the optimizer just fine. What version are you using? I tried with the latest version, 2.1.1.
If it's not an issue with the optimizer version you're using, I would try changing references of localStorage
to window.localStorage
and see if that make a difference.