javascript Uncaught ReferenceError: require is not defined

挑戰在一般的 html 網頁的 javascript 裡 require() 檔案, 顯示錯誤訊息:

Uncaught ReferenceError: require is not defined

Web browsers don’t support the require() function natively because it is part of Node.js’s module system (CommonJS), not part of standard JavaScript. To use modules in client-side JavaScript, you would generally use the ES6 import statement. However, this assumes that the script you’re importing is an ES6 module, and it must be served from a web server due to CORS (Cross-Origin Resource Sharing) policies in browsers.

If you’re trying to use a Node.js library in client-side code, you will often need to use a tool like Browserify or Webpack. These tools bundle your code and its dependencies into a single JavaScript file that can be included in your HTML.

If you are indeed trying to use Node.js and the error persists, it could be due to several reasons:

  1. The script is not running in a Node.js environment. Make sure you’re running your script with Node.js, e.g. node your_script.js in the command line.
  2. The module you’re trying to require is not installed. If you’re trying to require a third-party module, make sure it’s installed using npm install module_name.
  3. The path to the module is incorrect. If you’re trying to require a local file, make sure the path to the file is correct. For example, if you’re in the same directory as the file, the require statement would be require('./filename').

資料來源:
https://www.digitalocean.com/community/questions/uncaught-referenceerror-require-is-not-defined

除此之外, 是有其他解法, 例如 webpack:
https://github.com/scabbiaza/ramda-webpack-tree-shaking-examples

或 browserify
https://browserify.org/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *