SyntaxError: Cannot use import statement outside a module

问题

import Mock from 'mockjs'
var data = Mock.mock({
  // 属性 list 的值是一个数组,其中含有 1 到 10 个元素
  'list|1-10': [{
      // 属性 id 是一个自增数,起始值为 1,每次增 1
      'id|+1': 1
  }]
})
// 输出结果
console.log(JSON.stringify(data, null, 4))

这时我打算用node.js来运行它,但是报错了:

(node:15288) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module

解答

按照它的提示,两步走:
(1) npm init -y
(2) 在 package.json 中添加字段 type

{
  "name": "mock",
  "version": "1.0.0",
  "description": "",
  "main": "01.js",
  "type": "module", // 注意这里
  "dependencies": {
    "_commander@5.1.0@commander": "^5.1.0",
    "_mockjs@1.1.0@mockjs": "^1.1.0",
    "commander": "^5.1.0",
    "mockjs": "^1.1.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

(3) 添加完 node 01.js
{{uploading-image-562786.png(uploading...)}}