CommonJS là một module pattern hỗ trợ cho tất cả các phiên bản Node.js. Với CommonJS, JavaScript obj

https://viblo.asia/p/javascript-promises-classes-es6-modules-and-commonjs-07LKX48DKV4

// custom.js
const log = (message) => console.log(message)

module.exports = {log}

CommonJS không sử dụng từ khóa import mà sử dụng require function để import:

// index.js
const {log} = require('./custom.js')

log("CommonJS")

Vì CommonJS là một pattern của Node.js, do đó để sử dụng được phía frontend, chúng ta cần một số công cụ bên thứ 3, trong phần này mình sẽ sử dụng Browserify . Cài đặt:

npm install -g browserify

Sau đó chúng ta sẽ sử dụng browserify CLI để chuyển đổi file index.js thành file bundle.js bằng lệnh

browserify index.js > bundle.js

Bây giờ chúng ta có thể nhúng file bundle.js vào trong code html của chúng ta, trong tag script:

<!-- index.html -->
<script src="bundle.js"></script>

Sau khi load trang index.html, trong cửa sổ console của trình duyệt, chúng ta sẽ thu được kết quả CommonJS.

Tài liệu tham khảo: http://shop.oreilly.com/product/0636920049579.do

Cảm ơn các bạn đã đọc bài viết. Happy coding!!!

Last updated

Navigation

Lionel

@Copyright 2023