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

如何将本地HTML文件加载到NativeScript WebView中

Loading Local HTML Files into a NativeScript WebView

Hey there! It looks like you're already heading in the right direction to load a local HTML file into your NativeScript WebView—let's tweak those steps to make sure everything runs smoothly.

First, Validate Your Webpack Configuration

You’ve added the CopyWebpackPlugin to copy your index.html file, which is exactly what we need to get the file into your app’s bundled assets. A couple quick checks here:

  • Confirm your index.html is in the correct source directory (usually your project root or src folder). If it’s in src, adjust the glob path to src/index.html to ensure it’s picked up properly.
  • Make sure the plugin is placed in the plugins array of your webpack.config.js before the GenerateNativeScriptEntryPointsPlugin—order matters here.

Here’s a polished snippet of that section:

plugins: [
    new CopyWebpackPlugin([
        { from: { glob: "index.html" } }, // Update glob to "src/index.html" if your file lives there
        { from: { glob: "fonts/**" } },
        { from: { glob: "**/*.jpg" } },
        { from: { glob: "**/*.png" } },
        // Add globs for any other assets your HTML needs (CSS, JS, etc.)
        { from: { glob: "**/*.css" } },
        { from: { glob: "**/*.js" } }
    ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
    new nsWebpack.GenerateNativeScriptEntryPointsPlugin("bundle")
]

Fix the WebView Source Path

The most common misstep here is the src attribute in your main-page.xml. NativeScript uses the ~/ prefix to reference files in your app’s bundled assets folder (where the CopyWebpackPlugin places your index.html). Swap out index.html for ~/index.html:

<WebView row="1" loaded="onWebViewLoaded" id="myWebView" src="~/index.html"/>

Optional: Dynamic Loading via the Loaded Event

If you want to set the source programmatically (or need to add extra setup logic), use the onWebViewLoaded function in your main-page.js/main-page.ts:

export function onWebViewLoaded(args) {
    const webView = args.object;
    // Point directly to the bundled HTML file
    webView.src = "~/index.html";
}

Check Your Asset References

If your index.html links to local CSS, JS, or images, make sure those files are also copied via the CopyWebpackPlugin (like we added the CSS/JS globs above) and use relative paths correctly. For example, if you have a styles.css in the same folder as index.html, use <link rel="stylesheet" href="./styles.css">.

That’s it! Run ns run android or ns run ios again, and your WebView should load the local HTML file without any hiccups.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:47:33