查看: 50|回复: 0

TypeScript 如何使用 import 语法

[复制链接]

0

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2012-4-15
发表于 2021-1-11 11:02:00 | 显示全部楼层 |阅读模式
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);
  }
}
import { Header, Content, Footer } from "./components";
export default class Page {
  constructor() {
    new Header();
    new Content();
    new Footer();
  }
}

编译好的代码都是define开头的(这是 amd 规范的代码,不能直接在浏览器中运行,可以在 Node 中直接运行),这种代码在浏览器中是没办法被直接运行的,需要其他库(require.js)的支持。

引入现成的 CDN 的 require.js:

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>

在 html 里使用:

<body>
  <script>
    require(["page"], function (page) {
      new page.default();
    });
  </script>
</body>

可以看出这么做非常麻烦,但是我们可以用打包工具来完成这项工作,比如 webpack 和 Parcel 。参考:用 Parcel 打包 TypeScript 代码


相关文章:
用 Parcel 打包 TypeScript 代码
参考:
技术胖——TypeScript从入门到精通(24. TypeScript 如何使用 import 语法)



来源:https://www.cnblogs.com/xch-jiang/p/14261156.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部