😍Trình duyệt không có require, nhưng Node.js thì có. Với Browserify để trình duyệt cũng có (ok)

https://browserify.org/

Example chạy trực tiếp file app.js không được phải build bằng browserify ví dụ thành file bun.js

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./dist/bun.js"></script>
</head>
<body>
  AB
</body>
</html>

dist\app.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var add_1 = require("./add/add");
var result = (0, add_1.add)(1, 4);
console.log(result); // Output: 5
browserify  dist/app.js -o dist/bun.js

Bundle up your first module

Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.

Here is a tutorial on how to use Browserify on the command line to bundle up a simple file called main.js along with all of its dependencies:

main.js

var unique = require('uniq');

var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];

console.log(unique(data));

Install the uniq module with npm:

npm install uniq

Now recursively bundle up all the required modules starting at main.js into a single file called bundle.js with the browserify command:

browserify main.js -o bundle.js

Browserify parses the AST for require() calls to traverse the entire dependency graph of your project.Drop a single <script> tag into your html and you're done!

<script src="bundle.js"></script>

Last updated