問題
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...)}}
