打包
前言
在说打包前,有一些基础概念我们需要搞清楚。
- commonjs vs ES modules
- babel
ES module format
Official standard format to package js code for a reuse. most modern browsers natively support the modules.
load: import export: export
commonjs module format
Nodejs, support the cjs format by default. v13.2.0 has stable support for ES module.
load: require export: module.exports
commonjs versus ES module
usage
util.js
module.exports.hello = function (name) {
return `hello ${name}`;
};
usage.js
const { hello } = require('./utils');
consolel.log(hello('aliveAmy'));
how to enable ES modules in Node.js package?
- just change the file extension from
.js
to.mjs
or
- set package.json's module field
or
- babel: compile ES module syntax down to commonJS syntax :::
util.mjs
module.exports.hello = function (name) {
return `hello ${name}`;
};
usage.mjs
import { hello } from './utils.mjs';
consolel.log(hello('aliveAmy'));
require() get returns from module.exports. exports.XXX doesn't return by require(). :::
or
{
"name": "alive-amy",
"type": "module"
}
flexibility
import
can only be written in the beginning of the file
require
can be called anywhere in the code.
synchronous & asynchronous
commonJS: synchronous ES module: asynchronous
Turbopack
webpack
rollup
parceljs
yarn add --dev parcel