JS:将数组模块导入主脚本而不是 HTML

JS: import an array module into main script and not HTML

我是 JavaScript 的新手。我一直在寻找问题的答案,但无法弄清楚。

同样,我有一系列不同的选项(用于文本冒险游戏),我想将它们导入到主 JS 脚本中。问题是我在主脚本中从数组中调用了不同的选项,但它不起作用。

我在互联网上找到的答案适用于将函数从模块导入 HTML 代码,但这不是我要找的。

这是正在工作的代码:

const textElement = document.getElementById('text');
const buttonOptionsElement = document.getElementById('buttonOptions');

// keep track of what the character has on them

let state = {}
// function to start the game
function startGame() {
 state = {}
 showTextNode(1)

}

function showTextNode(textNodeIndex) {
 const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
 textElement.innerText = textNode.text
 while (buttonOptions.firstChild) {
   buttonOptions.removeChild(buttonOptions.firstChild)
 }

 textNode.options.forEach(option => {
   if(showOption(option)) {
     const button = document.createElement('button')
     button.innerText = option.text
     button.classList.add('btn')
     button.addEventListener('click', () => selectOption(option))
     buttonOptions.appendChild(button)
   }
 })
}

function showOption(option) {
 return option.requiredState == null || option.requiredState(state)
}

// function to get the element clicked
function selectOption(option) {
 const nextTextNodeId = option.nextText
 if (nextTextNodeId <= 0) {
   return startGame()
 }
 state = Object.assign(state, option.setState)
 showTextNode(nextTextNodeId)
}

const textNodes = [
 {
   id: 1,
   text: 'First scenario',
   options: [
     {
       text: 'Take goo',
       setState: { blueGoo: true},
       nextText: 2
     },
     {
       text: 'leave the goo',
     }
   ]
 },
 {
   id: 2,
   text: 'this is the second scenario.',
   options: [
     {
       text: 'trade the goo for a sword',
       requiredState: (currentState) => currentState.blueGoo,
       setState: { blueGoo: false, sword: true},
       nextText: 3
     }
]

startGame();

工作的代码完全是一回事,但我没有在main.js中有textNodes数组,而是有它在一个单独的文件中。我用以下行导入它来代替 const textNodes = [{},...,{}]

import { textNodes } from './modules/scenario.js'

emmm,口碑不够评论。基本上,您需要先查看调试会话的 JS 模块文档。可能需要检查 2 个地方:

  1. 模块js文件需要在HTML中声明为模块。

<script type="module" src="main.js"></script>

  1. 您需要在scenario.js导出相应的函数。

好吧,我发现了问题...这很荒谬,只是在 HTML 中我输入了 type="modules" 而不是 type="module"