Angular/Cordova: 在安卓设备上遇到MIME类型问题

3

我创建了一个Cordova应用程序,当创建新项目时,简单地提供默认的Angular欢迎页面。在浏览器中它能够正常工作,在Android Studio模拟器上运行它也能够正常工作。

但是当我在我的安卓设备上运行它时,我只能看到一个空白页面,并且控制台中出现以下错误:

polyfills-es2015.5728f680576ca47e99fe.js:1 Failed to load module script: The 
server responded with a non-JavaScript MIME type of "". Strict MIME type 
checking is enforced for module scripts per 
HTML spec.

main-es2015.734c1bff4ed0a6bbbd29.js:1 Failed to load module script: The 
server responded with a non-JavaScript MIME type of "". Strict MIME type 
checking is enforced for module scripts per HTML spec.

我可以通过编辑 Angular 创建的 dist/<project>/index.html 文件来解决这个问题。Angular 不再在创建的 <script> 标签中包含 type="text/javascript" 参数,而是如下所示:
<script src="runtime-es2015.858f8dd898b75fe86926.js" type="module"></script>
<script src="polyfills-es2015.5728f680576ca47e99fe.js" type="module"></script>
<script src="runtime-es5.741402d1d47331ce975c.js" nomodule></script>
<script src="polyfills-es5.7f43b971448d2fb49202.js" nomodule></script>
<script src="main-es2015.734c1bff4ed0a6bbbd29.js" type="module"></script>
<script src="main-es5.43ecaae92d6e77bfb1c5.js" nomodule></script>

如果我将其更改为type="text/javascript",该应用程序可以在我的设备上正确运行。

我该如何告诉Cordova在提供javascript文件时包含正确的MIME类型头?

2个回答

2
你可以在Angular项目中更新tsconfig.json文件:
"target": "es5",

如果您不想在tsconfig中更改目标,可以使用before_prepare钩子文件替换index.html中的内容。

在hooks文件夹中添加一个新文件夹并将其命名为“before_prepare”... 在before_prepare文件夹中添加一个新的js文件,例如命名为“01_switch_configuration.js”。

#!/usr/bin/env node

var fs = require('fs');
var path = require('path');

var rootdir = process.argv[2];

function replace_string_in_file(filename, to_replace, replace_with) {
    var data = fs.readFileSync(filename, 'utf8');
    var result = data.replace(new RegExp(to_replace, "g"), replace_with);
    fs.writeFileSync(filename, result, 'utf8');
}
if (rootdir) {
    var filestoreplace = ["www/index.html"];
    filestoreplace.forEach(function(val, index, array) {
        var fullfilename = path.join(rootdir, val);
        if (fs.existsSync(fullfilename)) {
            replace_string_in_file(fullfilename, 'type="module"', 'type="text/javascript"');
        } else {
            console.log("missing: " + fullfilename);
        }
    });
}

并运行您的项目


0

assets 可以通过定义一个 before_compile 钩子 来修复,该钩子会运行一个 shell 脚本:

sed -i 's/original/new/g' ./platforms/android/assets/index.html

这些正则表达式应该与nomoduletype="module"匹配,就像original一样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接