How to define a js package?
In orginal PIES, you should first declare the package in some where:
$package.register('a.b.c', './lib/example.js#X,Y;Z');
Then u can import it in any program:
$import(a.b.c);
...
var x = new X();
After importing, X and Y will be export into global scope.
If you want to use Z, you should write:
var p = $import(a.b.c);
...
var z = new p.Z();
This syntax and semantic is to align mozilla's js 2.0 draft.
But the new es4 spec is based on adobe's draft.
And I have read a lot of projects which provide some js package mechanism, and rethought the thing.
Below is my new design:
1. Define a new module:
new Module().
$import('a.b.X').
include('./test1.js').
include('./test2.js').
$export('a.b.Y').
end;
2. Import package:
$import(a.b.Y);
...
var x = new Y();
There is a significent change, instead of register a package, I choose to define a module. What's the difference? That is, the new design separate the package(namespace), module and source files.
A package is just a namespace, which is the name system to organize the code logically (and identify the creator).
A module is about scope, and the dependency. You can import many names(package) in a module or define many names(package) in a module.
In the traditional js practice, module and file are one to one map. But, currently there are many js compressor or packer or linker...In many big sites, a many small js source files will be pack into a single compressed js file, so just like jar for java or assembly for .net. That means module and deployment files should be separated.
My new design seperate these three things.
new Module().
$import('a.b.X').
include('./test1.js').
include('./test2.js').
$export('a.b.Y').
end;
These codes defines an new moudle, which includes to small source files test1.js and test2.js, and in these two files, they can reference X object, which under package a.b (so it has the full quarlified name a.b.X), and in one of the files, it will define a object Y, which will be exported into package a.b (so with the full quarlified name a.b.Y). This module will depend on another module which exports a.b.X, and any modules which import a.b.Y will depend on it (but you not need to define the dependency explictly).
I am also developing jsa(js achive or js assembly), which can pack many modules into one file. Not like simply merge, it won't cause name conflict.
本文介绍了一种新的JavaScript模块和包定义方案。该方案通过分离命名空间、模块及源文件来解决传统做法中的一些局限性,并支持复杂的依赖管理和打包压缩需求。
1816

被折叠的 条评论
为什么被折叠?



