使用srcipt引入js的情况下使用ES6的export的import语法

注:在此情况下使用,需要把script的type值设置为module ,默认情况下 type=“text/javascript”

案例:

idnex.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
	</body>
	<script src="api.js" type="module"></script>
	<script src="util.js" type="module"></script>
	<script type="module">
		import { Obj, argu } from './util.js'
		var a = argu(10);
		var b = Obj.add(10);
		var c = Obj.reduce(10);
		console.log('index',a, b, c)
	</script>
</html>

util.js

export function argu(argu){
	return argu+10;
}

var Obj = {
	add:function(argu){
		return argu+10;
	},
	reduce:function(argu){
		return argu-1;
	}
}

export { Obj }

api.js

import { Obj, argu } from './util.js'


var a = argu(10);
var b = Obj.add(10);
var c = Obj.reduce(10);
console.log(a, b, c)

尚未得到支持的 import 路径符号

// 支持
import {foo} from 'https://jakearchibald.com/utils/bar.js';
import {foo} from '/utils/bar.js';
import {foo} from './bar.js';
import {foo} from '../bar.js';

// 不支持
import {foo} from 'bar.js';
import {foo} from 'utils/bar.js';

有效的路径符号应当符合以下条件规则之一:

  • 完整的非相对路径。这样在将其传给new URL(moduleSpecifier)的时候才不会报错。
  • 以 / 开头。
  • 以 ./ 开头。
  • 以 …/ 开头。

其他形式的符号被保留下来,未来将用于其他功能(如引入[import]内置模块)。

发布了17 篇原创文章 · 获赞 43 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/mf_717714/article/details/84621691