基础教程,简单记录一下
模块化的使用
1.新建ex.js 并且声明变量:
var val='hello world'
export {val}
2.新建im.js 并且导入模块
import {val} from './ex'
console.log(val)
3.在命令行使用node命令运行im.js
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:1
import {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
报错
解决办法两个:
A.使用第一种,修改文件后缀 都修改成mjs结尾的文件
然后尝试运行:
并且修改im中的代码
import {val} from './ex.mjs'
console.log(val)
成功
B.添加配置文件
(node:6500) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
添加配置文件package.json
{
"type": "module"
}
运行成功
背后的故事:
ECMAScript Module规范
我们新建一个js文件
console.log(module)
输出如下:
D:\codingSpace\nodeImooc\chapter02>node ex.js
Module {
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'
]
}
文章评论