You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NativeScript启动前读取配置文件报错:unexpected token import

解决NativeScript app.js中"unexpected token import"错误及全局变量设置问题

Hey there! Let's break down what's going on here and fix your issue step by step.

The "unexpected token import" error pops up because NativeScript's default runtime treats app.js as a CommonJS module (the Node.js standard), which doesn't recognize ES6 import syntax out of the box. When you use import instead of the Node.js-style require, the runtime throws that error.


解决方案1:改用CommonJS的require语法(最稳妥)

Replace all your import statements with require calls. This is the most straightforward fix that works with NativeScript's default setup.

Here's a corrected example of your app.js (assuming your goal was to load a config file and set global variables):

const { application } = require("@nativescript/core");
const { knownFolders, File } = require("@nativescript/core/file-system");

// 检查配置文件并设置全局变量
function loadAppConfig() {
    const configFilePath = knownFolders.currentApp().path + "/config.json";
    if (File.exists(configFilePath)) {
        const configContent = File.fromPath(configFilePath).readTextSync();
        global.appConfig = JSON.parse(configContent);
        console.log("配置文件加载成功!");
    } else {
        // 配置文件不存在时使用默认值
        global.appConfig = { apiUrl: "https://your-default-api.com", debugMode: false };
        console.warn("未找到配置文件,使用默认配置");
    }
}

// 先执行配置检查逻辑
loadAppConfig();

// 启动应用
application.run({ moduleName: "app-root" });

解决方案2:让项目支持ES6模块(进阶)

If you prefer sticking with ES6 import syntax, you have two options:

  • Rename app.js to app.mjs: Node.js automatically recognizes .mjs files as ES modules. You'll need to update all imports/exports across your project to use ES6 syntax to match.
  • Add "type": "module" to your package.json: This tells Node.js to treat all .js files in the project as ES modules. Note that this might break some NativeScript plugins that rely on CommonJS, so be sure to test thoroughly.

关于全局变量的小提示

In NativeScript, you can safely attach global variables to either:

  1. The global object (like in the example above) — accessible from any file in your project directly.
  2. The application object, if you prefer a more NativeScript-specific approach:
    application.appConfig = { /* 你的配置内容 */ };
    

新手友好建议

If you're new to NativeScript, I'd highly recommend starting with the TypeScript template (ns create myApp --template @nativescript/template-blank-ts). TypeScript supports ES6+ syntax by default, and NativeScript's tooling is optimized for it — you'll run into far fewer syntax-related headaches like this one.

内容的提问来源于stack exchange,提问作者Urashx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:08:00