Importing
There are packages that work just in the browser, just in react, just for gatsby, or just for node
And there are some that work for multiple like debug
working for node and browsers
Module Types
ECMA Modules(import) webpack/babel often, async loaded
Absolute paths are currently not supported
Relative paths are resolved relative to current module path
automatically in strict mode, (mistakes into errors, simplifying/easier JS, anticpate future ECMA evolution)
CommonJS(require) node default, sync loaded
Have access to
__filename
and__dirname
.mjs
extension in node:
Uses ECMA, but can cause problems if you use CommonJS modules too
Can import commonjs files, but .js cant use .mjs
Use std/esm to use .mjs in .jsj
main.js
require = require("@std/esm")(module);
module.exports = require("./hi-web.mjs").default;
Access Node builtin modules
import * as path from 'path';
Require (CommonJS)
Exporting
//module.exports = router;
module.exports = {
insertOne,
queryByUniqueId
};
Importing
const conf = require("config");
const Phrase = require('../dao/phrase_dao');
###Import (EMCAScript)
Exporting
//export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
export const MODULES_BECAME_STANDARD_YEAR = 2015;
export default class User { // just add "default"
constructor(name) {
this.name = name;
}
}
Importing
import User from './user.js'; // not {User}, just User
new User('John');
import {sayHi, sayBye} from './say.js';
import * as say from './say.js';
Exporting Imports
//export imports
import d, {obj} from '...';
export {obj, d};
export {obj as name1, d as name2};
//re-export all named imports
export * from '...';
export * as name1 from '...';
//re-export some named imports
export {a, b as name1} from '...';
//re-export default import as default export
export {default} from '...';
//re-export default import as named export
export {default as name1} from '...';
Typescript
TypeScript 3.8 adds a new syntax for type-only imports and exports.
import type { SomeThing } from "./some-module.js";
export type { SomeThing };
import type
only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there’s no remnant of it at runtime. Similarly, export type
only provides an export that can be used for type contexts, and is also erased from TypeScript’s output.
Last updated