命名空间 namespace
命名空间(之前叫做“内部模块”)来管理变量, 避免污染全局
page.ts
namespace Home {
class Header {
constructor() {
const elem = document.createElement('div');
elem.innerText = 'This is Header';
document.body.appendChild(elem);
}
}
class Content {
constructor() {
const elem = document.createElement('div');
elem.innerText = 'This is Content';
document.body.appendChild(elem);
}
}
class Footer {
constructor() {
const elem = document.createElement('div');
elem.innerText = 'This is Footer';
document.body.appendChild(elem);
}
}
export class Page {
constructor() {
new Header();
new Content();
new Footer();
}
}
}
index.js
new Home.Page();
tsconfig.js
"module": "commonjs"
"outDir": "./dist",
"root": "./src"
打包多个文件到一个文件(AMD 方式)
components.ts
namespace Components {
export interface user {
name: string;
}
export class Header {
constructor() {
const elem = document.createElement('div');
elem.innerText = 'This is Header';
document.body.appendChild(elem);
}
}
export class Content {
constructor() {
const elem = document.createElement('div');
elem.innerText = 'This is Content';
document.body.appendChild(elem);
}
}
export class Footer {
constructor() {
const elem = document.createElement('div');
elem.innerText = 'This is Footer';
document.body.appendChild(elem);
}
}
}
page.ts
///<reference path="components.ts" />
namespace Home {
export namespace Dell {
export const teacher: Components.user = {
name: 'dell'
};
}
export class Page {
constructor() {
new Components.Header();
new Components.Content();
new Components.Footer();
new Components.Footer();
}
}
}
index.js
<script src="./dist/page.js" ></script>
<script>
new Home.Page()
</script>
tsconfig.json
"module": "amd" ,
"outFile": "./dist/page.js" /* Concatenate and emit output to single file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src"
4-9 import 对应的模块化
es的import实现模块管理
- commonjs(CMD)
- AMD
require引入模块
tsconfig.json
"module": "amd" ,
"outFile": "./dist/page.js" /* Concatenate and emit output to single file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src"
index.js
<script src="https://cdn.bootcdn.net/ajax/libs/require.js/2.3.6/require.js"></script>
<script src="./dist/page.js" ></script>
<script>
require(['page'], function() {
new page.default()
})
</script>
page.ts
import { Header, Content, Footer} from './components'
export default class Page {
constructor() {
new Header();
new Content();
new Footer();
}
}
4-10 使用Parcel打包TS代码
Parcel与wabpack相似, 不需要配置。
优势:
yarn init -y
tsc —init
yarn add parcel@next —dev
“start”: “parcel ./src/index.html”
tsconfig.json
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src"
index.html
<script src="./dist/page.ts" ></script>
代码仓库: