Basic tutorial, simply record


use of modularity


1. Create ex.js and declare variables:

 

var val='hello world'export {val}


2. Create im.js and import the module

import {val} from './ex'console.log(val)

3. Use the node command to run im.js on the command line

D:\codingSpace\nodeImooc\chapter02>node im.js(node:10092) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.(Use `node --trace-warnings ...` to show where the warning was created)D:\codingSpace\nodeImooc\chapter02\im.js:1import {val} from './ex'^^^^^^
SyntaxError: Cannot use import statement outside a module at wrapSafe (internal/modules/cjs/loader.js:1001:16) at Module._compile (internal/modules/cjs/loader.js:1049:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10) at Module.load (internal/modules/cjs/loader.js:950:32) at Function.Module._load (internal/modules/cjs/loader.js:790:12) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12) at internal/main/run_main_module.js:17:47

report an error

There are two solutions:

A. Using the first method, modify the file suffix to a file ending in mjs

picture

Then try to run:

and modify the code in im

import {val} from './ex.mjs'console.log(val)

picture

success

B. Add a configuration file

(node:6500) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

Add configuration file package.json

{  "type": "module"}

picture

run successfully

the story behind:

ECMAScript Module Specification


We create a new js file

console.log(module)

The output is as follows:

D:\codingSpace\nodeImooc\chapter02>node ex.jsModule {  id: '.',  path: 'D:\\codingSpace\\nodeImooc\\chapter02',  exports: {},  parent: null,  filename: 'D:\\codingSpace\\nodeImooc\\chapter02\\ex.js',  loaded: false,  children: [],  paths: [    'D:\\codingSpace\\nodeImooc\\chapter02\\node_modules',    'D:\\codingSpace\\nodeImooc\\node_modules',    'D:\\codingSpace\\node_modules',    'D:\\node_modules'  ]}