Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: require is not defined in svelte/sapper

Trying to create a blog-like application using svelte/sapper and so I'm currently writing the post to a file as a JSON object. However, when I try and use fs, I get the following error:

Uncaught ReferenceError: require is not defined

The file below is in the src/routes folder and is what handles the file writing function:

_write.js

function writeFile(obj) {
  var fs = require("fs");
  fs.writeFile('C:/Users/Toby/Documents/GitHub/political-web/src/routes/_posts.js', 'const posts = ' + obj + '; export default posts;', function (err) {
    if (err) throw err;
    console.log('Done!');
  });
}

export default writeFile;

Any ideas as to what I'm doing wrong?

like image 894
Toby King Avatar asked Feb 04 '26 19:02

Toby King


1 Answers

Not sure why you're getting that specific error — require should be defined when that code runs, unless you're somehow importing it in your client app (e.g. via a component).

Assuming that's not the case, and you're only importing _write.js from server code, rewrite it like this:

import fs from 'fs';

function writeFile(obj) {
  fs.writeFile('C:/Users/Toby/Documents/GitHub/political-web/src/routes/_posts.js', 'const posts = ' + obj + '; export default posts;', function (err) {
    if (err) throw err;
    console.log('Done!');
  });
}

export default writeFile;
like image 164
Rich Harris Avatar answered Feb 07 '26 09:02

Rich Harris