ๅไธๅๆ็ซ ,ๅฆๆๆๅๆณๆ้กไผผ SPA ้ฃ็จฎ routes ็ๅ่ฝ,่ฎ้่ค่ณๆบๅฆ jQuery ็ตฑไธไธๅ
่ฉฒๆ้บผๅฏฆๅ。
็ฎ้็ตๆง
| a.html
| b.html
| tsconfig.json
| webpack.config.js
+---app
|
\---src
| main.ts
| routes.ts
\---class
a.ts
b.ts
main.interface.ts
ๆๆ index.ts ๆนๆไบ main.ts,ๅขๅ ไบ,็จๅผ็ขผๅ
งๅฎนๅฆไธ:
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Typescript + Webpack</title>
<script src="app/main.js"></script>
</head>
<body id="a">
<div id="content"></div>
</body>
</html>
b.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Typescript + Webpack</title>
<script src="app/main.js"></script>
</head>
<body id="b">
<div id="content"></div>
</body>
</html>
main.ts
import $ from 'jquery';
import { routes } from './routes';
$(function () {
const classLoader = async (routeName: string): Promise<any> => {
const imported = await import('./class/' + routeName);
const className = routeName.toUpperCase();
return new imported[className]();
}
routes.forEach(route => {
if ($(`body#${route}`).is('*')) {
classLoader(route).then(target => target.init());
return false;
}
});
});
routes.ts
export const routes: string[] = [
'a',
'b'
]
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: {
main: {import: './src/main.ts'}
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
path: path.resolve(__dirname, 'app'),
},
};
main.interface.ts
export interface mainInterface {
init(): void
}
a.ts
import { mainInterface } from './main.interface';
import $ from 'jquery';
export class A implements mainInterface {
init(): void {
$('div#content').html('a');
}
}
b.ts
import { mainInterface } from './main.interface';
import $ from 'jquery';
export class B implements mainInterface {
init(): void {
$('div#content').html('b');
}
}
N.html ๅฐๆ N.ts,ๅฐๆๆ่ฆๅฐๆ็ class ่จญๅฎๅ ๅฐ routes.ts,main.ts ๆๅๆ
ๅตๆธฌๅฐ html ๆชๆก็ body ๆๆฒๆ็ธๅฐๆ็ id,ๆ็่ฉฑๅฐฑๅปๆ็ธๅฐๆ็ class,่็ธๅฐๆ็ class ็นผๆฟ interface ไธๅฎ่ฆๆ init() ้ๅ method,ๆ็บ้ๅ้ ้ขๆ่ฆๅ็้ ่จญไบไปถ,้ๆจฃ compile ็็ตๆ jQuery ๆๅ
ถไป็ๅฅไปถๅชๆๆไธไปฝ,ไธฆไธๅๅฐ้้ขไธๅ้ ้ขๆ้่ฆ็ๅ่ฝ。