【问题标题】:Angular/Cordova: MIME Type issue on android deviceAngular/Cordova:Android 设备上的 MIME 类型问题
【发布时间】:2019-10-07 02:07:29
【问题描述】:

我创建了一个 Cordova 应用程序,它在创建新项目时仅提供默认的 Angular 欢迎页面。它在浏览器中运行良好。通过 Android Studio 在模拟器上运行时效果很好。

当我在我的 android 设备上运行它时,我得到一个空白页面,并且控制台中出现以下错误:

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 类型标头?

【问题讨论】:

    标签: javascript android angular cordova


    【解决方案1】:

    您可以在 Angular 项目中更新您的 tsconfig.json:

    "target": "es5",
    

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

    在文件夹挂钩中添加新文件夹并将其命名为“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);
            }
        });
    }

    然后运行你的项目

    【讨论】:

      【解决方案2】:

      assets 可以通过定义一个运行 shell 脚本的before_compile hook 来修复:

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

      这些正则表达式可能应该匹配nomoduletype="module" 作为original

      【讨论】:

        猜你喜欢
        • 2019-11-01
        • 2017-08-17
        • 2015-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-10
        • 2013-10-20
        • 1970-01-01
        相关资源
        最近更新 更多