问题
I have created a Cordova application which simply serves the default Angular welcome page when creating a a new project. It works fine in the browser. It works fine when run it on an emulator via Android Studio.
When I run it on my android device I get a blank page and the following error is available in the console:
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.
I can fix this by editing by dist/<project>/index.html
created by Angular. Angular no longer includes the type="text/javascript"
parameters in the <script>
tags it creates. Instead they look like this:
<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>
If I change that to type="text/javascript"
the app runs correctly on my device.
How can I tell Cordova to include the correct MIME type headers when serving the javascript files?
回答1:
The assets
can be fixed by defining a before_compile
hook, which runs a shell script:
sed -i 's/original/new/g' ./platforms/android/assets/index.html
These regular expressions probably should match nomodule
and type="module"
as the original
.
回答2:
you can update your tsconfig.json in angular project:
"target": "es5",
if you don't want to change the target in tsconfig, you can use before_prepare hook file to replace content in index.html
in folder hooks add new folder and name it "before_prepare"... inside before_prepare folder add new js file and name it for example "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);
}
});
}
and run you project
来源:https://stackoverflow.com/questions/58262722/angular-cordova-mime-type-issue-on-android-device