喜大普奔node支持es6模块导入导出
-
在项目目录控制终端执行命令
npm init -y创建package.json文件,并添加一句"type": "module" -
新建一个
1.hello.js并输出console.log(__filename)此时会报错ReferenceError: __filename is not defined
解决办法
- 利用
import.meta
import { fileURLToPath } from 'url'
import { dirname } from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
console.log(__filename)
console.log(__dirname)
注解: node中文网未更新,node官网是有说明的,
ES不支持require, exports, module.exports, __filename, __dirname
详情点击 import.meta 查看