Home > Blockchain >  Uncaught ReferenceError: require is not defined (How to use a javascript library from the command li
Uncaught ReferenceError: require is not defined (How to use a javascript library from the command li

Time:10-25

I'm new to javascript and programming in general. I would like to use this: https://github.com/CesiumGS/gltf-pipeline It's a tool to convert models into compressed formats. This is my code:

const gltfPipeline = require("gltf-pipeline");
const fsExtra = require("fs-extra");
const processGltf = gltfPipeline.processGltf;
const gltf = fsExtra.readJsonSync("model.gltf");
const options = {
  dracoOptions: {
    compressionLevel: 10,
  },
  separateTextures: true,
};
processGltf(gltf, options).then(function (results) {
  fsExtra.writeJsonSync("modeldraco.gltf", results.gltf);
  console.log('done');
  const separateResources = results.separateResources;

  for (const relativePath in separateResources) {
    if (separateResources.hasOwnProperty(relativePath)) {
      const resource = separateResources[relativePath];
      fsExtra.writeFileSync(relativePath, resource);
    }
  }
}); 

I copied this file, saved it as compress.js (because it rhymes) and I then ran it with node compress.js - this is how I'd run a python file.

Error is: Cannot find module 'gltf-pipeline' which makes sense. So, I did:

node -r gltf-pipeline compress.js but I get the same error.

So, I moved to HTML/JS, where I made an index.html file and linked with a <script> tag compress.js and the gltf-pipeline index.js file. These are the errors:

index.js:3 Uncaught ReferenceError: module is not defined
    at index.js:3
(anonymous) @ index.js:3
compress.js:3 Uncaught ReferenceError: require is not defined

So how is this done? Either as a webpage or command line would be helpful. This is my folder structure by the way, maybe that's the issue.

basefolder|
          |- gltf-pipeline| library files in here
          |- compress.js
          |- index.html
          |- model.gltf

gltf-pipeline works when used as a command line tool.

CodePudding user response:

No.

You can't do that with Javascript.

JS is served to the client. Whilst NodeJS runs on a server.

These are the diffrences between node and browser JS.

also for the module error try

npm install gltf-pipeline

Look at NPM to install Node Packages Also take a look at the NodeJS Tutorial

  • Related