npm i init --y npm i webpack -D npm i webpack-cli -D npm i @types/firefox-webext-browser @types/chrome -D // 瀏覽器擴展API提示
tsc --init npm i typescript ts-loader -D
設置tsconfig.json
配置文件
{ "compilerOptions": { "target": "ES2016", "module": "commonjs", // ts-node 不支持 commonjs 以外的任何模塊語法 "allowJs": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "moduleResolution": "node" }, "exclude": ["node_modules"], "include": ["./src/**/*.ts"] }
讓配置文件支持typescript
npm i ts-node @types/node @types/webpack -D
創(chuàng)建webpack.config.ts
配置文件
import path from "path"; import webpack from "webpack"; const config: webpack.Configuration = { mode: "production", entry: "./src/index.ts", output: { path: path.resolve(__dirname, "dist"), filename: "[name].bundle.js", }, module: { rules: [ { test: /\.tsx?$/, use: "ts-loader", exclude: /node_modules/, }, ], }, resolve: { extensions: [".tsx", ".ts", ".js"], }, }; export default config;
配置package.json
{ "scripts": { "build": "webpack --config webpack.config.ts" } }
創(chuàng)建文件./src/index.ts
const test = <T>(value: T) => { return value; }; const d = test(12); console.log(d);
在端執(zhí)行 npm run build
, 如果dist
目錄下生成了.bundle.js
文件則成功
npm i vue npm i vue-loader -D npm i vue-template-compiler -D
tsconfig.json
文件調整
{ "exclude": ["node_modules", "dist"], "include": ["./src/**/*.ts", "./src/**/*.vue", "./src/**/*.js"] }
webpack.config.ts
文件調整
const VueLoaderPlugin = require("vue-loader/lib/plugin"); { module: { rules: [ { test: /\.vue$/, loader: "vue-loader", }, { test: /\.tsx?$/, loader: "ts-loader", options: { appendTsSuffixTo: [/\.vue$/], }, exclude: /node_modules/, }, ], }, plugins: [new VueLoaderPlugin()], }
類寫法需要安裝
npm i vue-class-component -D npm i vue-property-decorator -D
typescript
只能解析ts
文件,無法解析vue
文件,所以要做一個模塊聲明
聲明文件shims-vue.d.ts
declare module "*.vue" { import Vue from "vue"; export default Vue; }
npm i sass-loader node-sass -D npm i style-loader css-loader sass-loader -D
webpack.config.ts
配置文件調整
module: { rules: [ ... // 普通的 `.scss` 文件和 `*.vue` 文件中的 // `<style lang="scss">` 塊都應用它 { test: /\.scss$/, use: ["style-loader","css-loader", "sass-loader"], }, ],
聯(lián)系客服