SyntaxError: Cannot use import statement outside a module
阿新 • • 發佈:2020-07-19
問題
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": { "[email protected]@commander": "^5.1.0", "[email protected]@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...)}}