解决模块导入语法错误:如何在app.js中导入xState状态机MYSM.js
解决导入XState状态机的报错问题
核心问题分析
报错SyntaxError: Cannot use import statement outside a module的直接原因是app.js未被标记为ES模块,同时还存在TypeScript语法不兼容、XState导入方式错误、路径配置不当等隐藏问题。
具体修复步骤
1. 修正app.js的脚本加载类型
在index.html中,将app.js的script标签类型从text/javascript改为type="module"——只有模块脚本才能使用import语句。同时把路径中的~/替换为浏览器可识别的相对路径(如./js/)或绝对路径:
<script type="module" src="./js/app.js"></script>
2. 移除MYSM.js中的TypeScript语法
浏览器原生JS不支持interface语法,直接删除export interface MYSMContext代码块,XState的上下文用普通JS对象定义即可:
// MYSM.js import { createMachine, interpret, assign } from 'https://unpkg.com/xstate@4/dist/xstate.web.js'; export const mySM = createMachine({ context: { returnCode: undefined, errorMessage: undefined }, // 其他状态机配置代码 });
3. 调整XState的导入方式
模块模式下不能直接从全局XState对象取成员,需通过ES模块导入获取;同时index.html中无需重复引入XState脚本,保留一个即可:
<!-- index.html中保留这一行即可 --> <script type="module" src="https://unpkg.com/xstate@4/dist/xstate.web.js"></script>
4. 修复app.js的语法错误
app.js中对象字面量的分号需改为逗号:
// app.js import { mySM } from './MYSM.js'; const newContext = { returnCode: 0, errorMessage: '' }; // 把;改为, const dynamicSM = mySM.withContext(newContext); const myService = interpret(dynamicSM).start();
最终完整代码示例
index.html
<!-- xState State Machine--> <script type="module" src="https://unpkg.com/xstate@4/dist/xstate.web.js"></script> <script type="module" src="./js/MYSM.js"></script> <script type="module" src="./js/app.js"></script>
MYSM.js
import { createMachine, interpret, assign } from 'https://unpkg.com/xstate@4/dist/xstate.web.js'; export const mySM = createMachine({ id: 'mySM', initial: 'idle', context: { returnCode: undefined, errorMessage: undefined }, states: { idle: { // 状态逻辑配置 } } });
app.js
import { mySM } from './MYSM.js'; const newContext = { returnCode: 0, errorMessage: '' }; const dynamicSM = mySM.withContext(newContext); const myService = interpret(dynamicSM).start();
内容的提问来源于stack exchange,提问作者SoftwareDveloper
相关产品推荐
相关产品推荐

