因為工作的關係接觸了 angular,所以學習了 typescript,覺得這工具很好用,於是希望在非 angular 的環境下寫 js 時也用 typescript,這時要借用 webpack 幫忙打包成 browser 可以使用的內容。
目錄結構
| ├─app |
| └─src |
| │ index.ts |
| │ |
| └─class |
| chan.ts |
| │ index.html |
| │ tsconfig.json |
| │ webpack.config.js |
config
tsconfig.json
| { |
| "compilerOptions": { |
| "allowSyntheticDefaultImports": true, |
| "noImplicitAny": true, |
| "module": "es6", |
| "target": "es5", |
| "allowJs": true |
| } |
| } |
typescript 的基礎配置
webpack.config.js
| const path = require('path'); |
| |
| module.exports = { |
| mode: 'development', |
| entry: { |
| index: {import: './src/index.ts'} |
| }, |
| module: { |
| rules: [ |
| { |
| test: /\.tsx?$/, |
| use: 'ts-loader', |
| exclude: /node_modules/, |
| }, |
| ], |
| }, |
| resolve: { |
| extensions: ['.tsx', '.ts', '.js'], |
| }, |
| output: { |
| path: path.resolve(__dirname, 'app'), |
| }, |
| }; |
webpack 的配置,會掃描 entry 我指定的檔案輸出到 app
同樣的檔名,用非 spa 的方式開發往往還是不同頁面使用不同的 js,所以這個架構對 user 並不能節省資源,因為每個 js 都會包一份 jquery,只是對開發者方便的工具而已,除非你有把握把程式寫到每個頁面隔離不互相干擾,那就可以一支檔案打天下,也是 spa 的運作方式。
npm i --save webpack webpack-cli typescript ts-loader
安裝 compiler 需要的工具
使用方式
npm i -s jquery dayjs
index.html
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>Typescript + Webpack</title> |
| <script src="app/index.js"></script> |
| </head> |
| <body> |
| <div id="content"></div> |
| </body> |
| </html> |
index.ts
| import $ from 'jquery'; |
| import { Chan } from './class/chan'; |
| |
| $(function () { |
| const chan = new Chan(); |
| |
| $('div#content').html(chan.getNow()); |
| }); |
chan.ts
| import dayjs from 'dayjs'; |
| |
| export class Chan { |
| public getNow(): string { |
| return dayjs().toString(); |
| } |
| } |
使用 webpack compiler 之後我們頁面上的 div#content
會出現 Fri, 29 Jan 2021 09:09:52 GMT,大功告成。