在这篇文章中,我们将带领您了解JavaScriptModulePattern:In-Depth的全貌,同时,我们还将为您介绍有关Failedtoloadmodulescript:Theserverre
在这篇文章中,我们将带领您了解JavaScript Module Pattern: In-Depth的全貌,同时,我们还将为您介绍有关Failed to load module script: The server responded with a non-JavaScript MIME type of “text/html”.、javascript - php module.sodll & java.class、javascript document.compatMode兼容性_javascript技巧、JavaScript ES6 Module模块详解的知识,以帮助您更好地理解这个主题。
本文目录一览:- JavaScript Module Pattern: In-Depth
- Failed to load module script: The server responded with a non-JavaScript MIME type of “text/html”.
- javascript - php module.sodll & java.class
- javascript document.compatMode兼容性_javascript技巧
- JavaScript ES6 Module模块详解
JavaScript Module Pattern: In-Depth
NOTE: This referenced article is obviously a bit old it is though a great one, which will lead you to wide areas in implementing module-based JS programming. So, if you are interested in modular means with JS programming, please Go on reading...
The module pattern is a common JavaScript coding pattern. It’s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I’ll review the basics and cover some truly remarkable advanced topics, including one which I think is original.
The Basics
We’ll start out with a simple overview of the module pattern, which has been well-known since Eric Miraglia (of YUI) first blogged about it three years ago. If you’re already familiar with the module pattern, feel free to skip ahead to “Advanced Patterns”.
Anonymous Closures
This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We’ll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.
(function () { // ... all vars and functions are in this scope only // still maintains access to all globals }());
Notice the ()
around the anonymous function. This is required by the language, since statements that begin with the tokenfunction
are always considered to be function declarations. Including ()
creates a function expression instead.
Global Import
JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var
statement for that name. If none is found, that variable is assumed to be global. If it’s used in an assignment, the global is created if it doesn’t already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.
Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, weimport them into our code, which is both clearer and faster than implied globals. Here’s an example:
(function ($, YAHOO) { // now have access to globals jQuery (as $) and YAHOO in this code }(jQuery, YAHOO));
Module Export
Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value. Doing so will complete the basic module pattern, so here’s a complete example:
var MODULE = (function () { var my = {}, privateVariable = 1; function privateMethod() { // ... } my.moduleProperty = 1; my.moduleMethod = function () { // ... }; return my; }());
Notice that we’ve declared a global module named MODULE
, with two public properties: a method namedMODULE.moduleMethod
and a variable named MODULE.moduleProperty
. In addition, it maintains private internal stateusing the closure of the anonymous function. Also, we can easily import needed globals, using the pattern we learned above.
Advanced Patterns
While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named MODULE
.
Augmentation
One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to augment modules. First, we import the module, then we add properties, then we export it. Here’s an example, augmenting our MODULE
from above:
var MODULE = (function (my) { my.anotherMethod = function () { // added method... }; return my; }(MODULE));
We use the var
keyword again for consistency, even though it’s not necessary. After this code has run, our module will have gained a new public method named MODULE.anotherMethod
. This augmentation file will also maintain its own private internal state and imports.
Loose Augmentation
While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn’t always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with loose augmentation. Each file should have the following structure:
var MODULE = (function (my) { // add capabilities... return my; }(MODULE || {}));
In this pattern, the var
statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like LABjs and load all of your module files in parallel, without needing to block.
Tight Augmentation
While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). Tight augmentation implies a set loading order, but allows overrides. Here is a simple example (augmenting our original MODULE
):
var MODULE = (function (my) { var old_moduleMethod = my.moduleMethod; my.moduleMethod = function () { // method override, has access to old through old_moduleMethod... }; return my; }(MODULE));
Here we’ve overridden MODULE.moduleMethod
, but maintain a reference to the original method, if needed.
Cloning and Inheritance
var MODULE_TWO = (function (old) { var my = {}, key; for (key in old) { if (old.hasOwnProperty(key)) { my[key] = old[key]; } } var super_moduleMethod = old.moduleMethod; my.moduleMethod = function () { // override method on the clone, access to super through super_moduleMethod }; return my; }(MODULE));
This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility. As I’ve written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval
. Nevertheless, I’ve included it for completeness.
Cross-File Private State
One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that willmaintain private state across all augmentations:
var MODULE = (function (my) { var _private = my._private = my._private || {}, _seal = my._seal = my._seal || function () { delete my._private; delete my._seal; delete my._unseal; }, _unseal = my._unseal = my._unseal || function () { my._private = _private; my._seal = _seal; my._unseal = _unseal; }; // permanent access to _private, _seal, and _unseal return my; }(MODULE || {}));
Any file can set properties on their local variable _private
, and it will be immediately available to the others. Once this module has loaded completely, the application should call MODULE._seal()
, which will prevent external access to the internal_private
. If this module were to be augmented again, further in the application’s lifetime, one of the internal methods, in any file, can call _unseal()
before loading the new file, and call _seal()
again after it has been executed. This pattern occurred to me today while I was at work, I have not seen this elsewhere. I think this is a very useful pattern, and would have been worth writing about all on its own.
Sub-modules
Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:
MODULE.sub = (function () { var my = {}; // ... return my; }());
While this may have been obvious, I thought it worth including. Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.
Conclusions
Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I’d combine loose augmentation, private state, and sub-modules.
I haven’t touched on performance here at all, but I’d like to put in one quick note: The module pattern is good for performance. It minifies really well, which makes downloading the code faster. Using loose augmentation allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.
To close, here’s an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I’ve left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.
var UTIL = (function (parent, $) { var my = parent.ajax = parent.ajax || {}; my.get = function (url, params, callback) { // ok, so I''m cheating a bit :) return $.getJSON(url, params, callback); }; // etc... return parent; }(UTIL || {}, jQuery));
I hope this has been useful, and please leave a comment to share your thoughts. Now, go forth and write better, more modular JavaScript!
登录乐搏学院官网 http://www.learnbo.com/
或关注我们的官方微博微信,还有更多惊喜哦~
Failed to load module script: The server responded with a non-JavaScript MIME type of “text/html”.
vue3+vite打包以后,项目切换路由触发(偶发触发)报:
After using vue-router, there is an error in packaging and running # Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
Failed to fetch dynamically imported module.....
确实应该是vite2.xx的bug https://github.com/vitejs/vite/issues/863
注意: 在使用vue3+vite时候,只发现vue-router切换时触发此现象
问题:
// vue3+vite此种异步路由引入方法 开发调试时确实没有问题,但是vite打包以后就会触发报错
routes: [
{
path: "/",
name: "Home",
component: import(`../views/${view}.vue`)
}
]
解决方法:
// 这样引用虽然解决了问题(浏览器会提醒,不用管),但是在一些win10自带的低版本edge浏览器中还是会稀有触发
// 应该确实是vite的兼容性bug问题
import { defineAsyncComponent } from ''vue''; //异步组挂载器
routes: [
{
path: "/",
name: "Home",
component: defineAsyncComponent(() => import(''../views/Home.vue''));
},
{
path: "/about",
name: "About",
component: defineAsyncComponent(() => import(''../views/About.vue''));
}
]
———————————————————— 2023年年初更新 Vite在升级到Vite3.x之后此问题已不存在,各种浏览器多次测试后也没有触发,如果还报类似的错误,请仔细检查路由导入写法是否正确。
后续持续跟进中...
javascript - php module.sodll & java.class
php的extension dll文件(wind) so文件(liunx)
以及java的class文件
他们是否都是字节码文件?
回复内容:
php的extension dll文件(wind) so文件(liunx)
以及java的class文件
他们是否都是字节码文件?
php的extension只有在windows上是.dll文件,在linux上同样是.so文件。它与其它.so文件或.dll文件的格式是一样的。
Linux的.so文件是机器码,对应于Windows下的.dll文件,被称为动态链接库。.so文件与.dll文件的区别是文件格式不同,.so文件格式是ELF,.dll文件格式是PE。
java的class是java字节码,是平台无关的,只能运行于java虚拟机中。
dll和so都是x86二进制代码,但是格式不太一样。
java的class文件是jvm中间代码,可以用jd-gui反编译成java源码来看。
都是二进制文件,参考这里 http://baike.baidu.com/view/560330.htm
javascript document.compatMode兼容性_javascript技巧
IE对盒模型的渲染在 Standards Mode和Quirks Mode是有很大差别的,在Standards Mode下对于盒模型的解释和其他的标准浏览器是一样,但在Quirks Mode模式下则有很大差别,而在不声明Doctype的情况下,IE默认又是Quirks Mode。所以为兼容性考虑,我们可能需要获取当前的文档渲染方式。
document.compatMode正好派上用场,它有两种可能的返回值:BackCompat和CSS1Compat。
BackCompat:标准兼容模式关闭。浏览器客户区宽度是document.body.clientWidth;CSS1Compat:标准兼容模式开启。 浏览器客户区宽度是document.documentElement.clientWidth。
那么写了个准确获取网页客户区的宽高、滚动条宽高、滚动条Left和Top的代码:
if (document.compatMode == "BackCompat") {
cWidth = document.body.clientWidth;
cHeight = document.body.clientHeight;
sWidth = document.body.scrollWidth;
sHeight = document.body.scrollHeight;
sLeft = document.body.scrollLeft;
sTop = document.body.scrollTop;
}
else { //document.compatMode == "CSS1Compat"
cWidth = document.documentElement.clientWidth;
cHeight = document.documentElement.clientHeight;
sWidth = document.documentElement.scrollWidth;
sHeight = document.documentElement.scrollHeight;
sLeft = document.documentElement.scrollLeft == 0 ? document.body.scrollLeft : document.documentElement.scrollLeft;
sTop = document.documentElement.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
}
JavaScript ES6 Module模块详解
0.什么是Module
历史上,JavaScript 一直没有模块(module)体系,无法将一个大程序拆分成互相依赖的小文件,再用简单的方法拼装起来。其他语言都有这项功能,比如 Ruby 的require、Python 的import,甚至就连 CSS 都有@import,但是 JavaScript 任何这方面的支持都没有,这对开发大型的、复杂的项目形成了巨大障碍。
在 ES6 之前,社区制定了一些模块加载方案,最主要的有 CommonJS 和 AMD 两种。ES6 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。ES6 模块不是对象,而是通过export命令显式指定输出的代码,再通过import命令输入。
模块系统主要解决的问题:
- 模块化的问题
- 消除全局变量
- 管理加载顺序
1.Module 的加载
使用 < script >标签加载模块时需要添加 type=“module”。
1.1 方式一
<script type="module"> import module from "./module.js"; </script>
1.2 方式二
<script src="./module.js" type="module"></script>
2.导出和导入
2.1 一个模块的导出可以被其它模块导入,并访问。
例1:使用About.js调用Base.js内的Base对象,并在首页打印。
index.html
<script type="module"> import About from "./js/About.js"; console.log(About); </script>
Base.js
const Base = { nick: ''admin'', age: 19 } export default Base;
About.js
import Base from ''../js/Base.js''; const src = `nick:${Base.nick},age:${Base.age}.`; export default src;
输出结果:
nick:admin,age:19.
2.2 没有导出,也可以将其导入
例2:About.js不导出,在首页将其导入。
index.html
<script type="module"> import "./js/About.js"; </script>
About.js
const src = ''Hello World!''; console.log(src);
输出结果:
Hello World!
2.3 被导入的代码都会执行一遍,也仅会执行一遍
例3:导入3次About.js,观察导出结果。
index.html
<script type="module"> import "./js/About.js"; import "./js/About.js"; import "./js/About.js"; </script>
About.js
const src = ''Hello World!''; console.log(src);
输出结果:
Hello World!
3.export default 和对应的 import
export default 用于导出一个默认值,一个模块只能有一个。
使用 export default 进行导出时,import 的名字可以随意起。
例4:使用 export default 进行导出,import 的名字随意起。
index.html
<script type="module"> import bbb from "./js/About.js"; console.log(bbb); </script>
About.js
const src = ''Hello World!''; export default src;
输出结果:
Hello World!
4.export 和对应的 import
使用 export 进行导出时,import 的名字不能随意起。
例5:使用 export 进行导出。
index.html
<script type="module"> import { age, nick } from "./js/About.js"; console.log(nick, age); </script>
About.js
const age = 18; export {age}; // export age; × // export const age = 18; √ export const nick = ''admin'';
输出结果:
admin 18
5.Module 的注意事项
1.模块中,顶层的 this 指向 undefined;
2import 具有提升效果,会提升到整个模块的头部,率先执行;
3.import 执行的时候,代码还没执行;
4.import 和 export 只能在模块的顶层,不能在代码块中执行;
5.import() 可以按条件导入;
6.复合写法导出的,无法在当前模块中使用
复合写法,导入后导出:
export About from ''./js/About.js'';
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!
- Javascript Constructor构造器模式与Module模块模式
- 解析Javascript设计模式Revealing Module 揭示模式单例模式
- JS中ESModule和commonjs介绍及使用区别
- 全面解析JavaScript Module模式
- JS module的导出和导入的实现代码
- JavaScript面试Module Federation实现原理详解
今天关于JavaScript Module Pattern: In-Depth的讲解已经结束,谢谢您的阅读,如果想了解更多关于Failed to load module script: The server responded with a non-JavaScript MIME type of “text/html”.、javascript - php module.sodll & java.class、javascript document.compatMode兼容性_javascript技巧、JavaScript ES6 Module模块详解的相关知识,请在本站搜索。
本文标签: