简体   繁体   中英

ReferenceError: Can't find variable: require - JQuery error

I use this code in my .js file which is part of web site that is used via npm global http-server:

function getParsedStorage() {
  let fs = require('fs');
  return JSON.parse(fs.readFileSync('./../manager-data.json', 'utf8'));
}

and get errors:

jQuery.Deferred exception: Can't find variable: require (2) (exceptionHook — jquery.min.js:2:31584)

ReferenceError: Can't find variable: require (jquery.min.js:2:31697)

I've installed file-system package with npm install file-system --save but that didn't change anything.

It looks to me like you're attempting to make use of Node.js's require function from within a web browser without using a module system that provides a compatible require method.

Without additional information I can't be certain, however my advice would be to investigate a module loader like Require.js , SystemJS or Browserify which should all enable you to make use of this syntax in your module.

That being said, for the use case you're describing (accessing a JSON file from a website) you may be better served using a simple XHRHttpRequest or the fetch API .

The following is an example which makes use of the fetch API to return the parsed JSON file content.

// Returns a Promise that resolves to the parsed storage data
// NOTE: Lacks any error handling
function getParsedStorage() {
  return fetch("../manager-data.json").then(response => response.json())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM