node环境下SyntaxError: Cannot use import statement outside a module

3,119 阅读1分钟

一、报错信息:

    SyntaxError: Cannot use import statement outside a module
    意思是:不能在模块外部使用import语句

image.png

二、报错原因

  1. node最早只支持CommonJS的模块化方案,所以ES6的模块化方案用不了
  2. node v13.2.0之后开始实验性的支持ES6的模块化方案,不过需要在package.json中设置"type": "module"

CommonJS模块化:

  • 导出:module.exports = {...}
  • 导入:var tracker = require('./tracker')

ES6模块化:

  • 导出:export default {...}export const add = () => {}
  • 导入:import tracker from './tracker.js'import { add } from './utils.js'

三、解决

  1. 升级node版本
  2. 设置"type": "module"