typescript+webpack+vscode

準備工做
事先安裝好 Node.jsvscodehtml

項目建立

在文件夾空白處單擊鼠標右鍵,選擇 在此處打開Powershell窗口.node

1.初始化項目

npm init

回答一系列的問題(也能夠直接回車使用默認值)後,在當前項目文件夾中會出現一個package.json的配置文件。webpack

{
  "name": "ts_webpack_vscode",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

2.安裝所需的基本模塊

Powershell窗口或者vscode中新建終端 輸入指令:es6

npm install --save-dev webpack webpack-cli typescript ts-loader

使用vscode 打開此項目web

3.添加配置文件

在項目根目錄建立新文件(tsconfig.json),即TypeScipt的配置文件.
下面是修改過的配置,簡單介紹下:chrome

sourcemap 是否生成.map文件
declaration 是否生成.d.ts文件
declarationDir .d.ts文件存放目錄
exclude 編譯時候忽略的文件typescript

{
    "compilerOptions": {
        "module": "es6",
        "target": "es5",
        "sourceMap": true,
        "declaration": true,
        "declarationDir": "./dist/typing",
        "lib": [
            "webworker",
            "es6",
            "es5",
            "dom"
          ]
    },
    
    "exclude": [
        "node_moudles",
        "dist"
    ]
}

在項目根目錄建立新文件(webpack.config.js),即webpack配置文件.
resolve.modules 編譯搜索目錄
ts-loader 編譯typescript工具
簡單介紹設置:
entry 項目入口(啓動)
output 生成文件地址shell

const path = require('path'); 
module.exports = {
    mode: 'development',
    entry: './src/main.ts',//入口文件
    output: {
        filename: 'main.js',//編譯出來的文件名
        path: path.resolve(__dirname, 'dist'),//編譯文件所在目錄   
        publicPath: '/dist/',//靜態資源目錄,能夠設爲「編譯文件所在目錄」, 代碼自動編譯,網頁自動刷新
    },
    module: {
        rules: [
            {
                // For our normal typescript
                test: /\.ts?$/,
                use: [
                    {
                        loader: 'ts-loader'
                    }
                ],
                exclude: /(?:node_modules)/,
            },
        ]
    },
    resolve: {
        modules: [
            'src',
            'node_modules'
        ],
        extensions: [
            '.js',
            '.ts'
        ]
    } 
 };

4.寫點代碼

在根目錄建立 src文件夾,在src文件夾下新建main.ts(即webpack 配置中入口)npm

console.log("hello typescript + webpack + vscode!");

在package.json中寫入編譯指令 "build"json

"scripts": {
    "build":"webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

在vscode終端中 或 Powershell(二者等同)輸入

npm run build

編譯生成mian.js 以及.d.ts文件

5.網頁運行項目

在根目下新建index.html文件,src="dist/main.js",即生成文件地址。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TypeScript + Webpack 4</title>
</head>
<body>

<script src="dist/main.js"></script>
</body>
</html>

安裝 webpack-dev-server 模塊

npm install --save-dev webpack-dev-server

在package.json中寫入新指令 「dev」

"scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

在vscode終端中 或 Powershell(二者等同)輸入

npm run dev

能夠看到:

PS D:\Git\_web3d\ts_webpack_vscode> npm run dev

    > ts_webpack_vscode@1.0.0 dev D:\Git\_web3d\ts_webpack_vscode
    > webpack-dev-server
    
    i 「wds」: Project is running at http://localhost:8080/
    i 「wds」: webpack output is served from /
    i 「wdm」: Hash: 7f042dbc150a27e0ecd3
    Version: webpack 4.21.0
    Time: 2396ms
    Built at: 2018-10-20 20:45:23
               Asset     Size  Chunks             Chunk Names
             main.js  338 KiB    main  [emitted]  main
    typing\main.d.ts  0 bytes          [emitted]
    Entrypoint main = main.js
    .........

點擊http://localhost:8080/便可啓動瀏覽器打開該連接,F12-》console中看到

hello typescript + webpack + vscode!

運行項目完結

完善項目

使用中遇到的一些問題

1.自定義server

在webpack.config.js中添加 server自定義配置。好處之一多個項目就不會端口衝突。

compress 是否壓縮
host localhost或 其餘1.1.1.1
prot 自定義端口

module.exports = {
    ...,
    devServer: {
        hot: true,
        compress: true,
        host: 'localhost',
        port: 8888
  },
  ...
}

從新啓動server,便可產生新的 地址.

1.1 在vscode中 F5啓動項目

在vscode中按F5,選擇環境 chorme,自動生成配置文件launch.js ,修改配置中的url爲server中設置的端口地址。

{
    // 使用 IntelliSense 瞭解相關屬性。 
    // 懸停以查看現有屬性的描述。
    // 欲瞭解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8888",
            "webRoot": "${workspaceFolder}"
        }
    ]
}

按下F5便可chorme中啓動項目.

2.生成獨立的.map文件

安裝source-map-loader 模塊

npm i -D source-map-loader

修改webpack.config.js配置

module.exports = {
    ...,
    
    devtool:'source-map',
    
    ....
}

devtool設置:

eval: 生成代碼 每一個模塊都被eval執行,而且存在@sourceURL
cheap-eval-source-map: 轉換代碼(行內) 每一個模塊被eval執行,而且sourcemap做爲eval的一個dataurl
cheap-module-eval-source-map: 原始代碼(只有行內) 一樣道理,可是更高的質量和更低的性能
eval-source-map: 原始代碼 一樣道理,可是最高的質量和最低的性能
cheap-source-map: 轉換代碼(行內) 生成的sourcemap沒有列映射,從loaders生成的sourcemap沒有被使用
cheap-module-source-map: 原始代碼(只有行內) 與上面同樣除了每行特色的從loader中進行映射
source-map: 原始代碼 最好的sourcemap質量有完整的結果,可是會很慢

從新執行編譯指令 npm run build,能夠看到在dist下生成了新文件main.js.map.

3.合併.d.ts文件

添加測試代碼hello.ts

export class dome
{
    static sayWord(value:string)
    {
        console.warn("dome test world:"+value);
    }
}

修改main.ts

import { dome } from "./hello";

console.log("hello typescript + webpack + vscode!");

dome.sayWord("@@@@@@@@@");

代碼結構

---src
-----hello.ts
-----main.ts

從新編譯能夠看到 dist/typing下有2個.d.ts文件.和.ts一一對應。

安裝webpack-dts-bundle

npm i -D webpack-dts-bundle

修改webpack.config.js

module.exports = {
        .......,
        
        plugins: [
            new DtsBundlePlugin()
        ],
        ....
        
    };
    
function DtsBundlePlugin() { }
DtsBundlePlugin.prototype.apply = function (compiler)
{
    compiler.plugin('done', function ()
    {
        var dts = require('dts-bundle');
        var rootDir = path.resolve(__dirname);
        dts.bundle({
            name: 'test',
            main: rootDir + '/dist/**/*.d.ts',
            out: rootDir + '/dist/main.d.ts',
            removeSource: false,
            outputAsModuleFolder: true,
            exclude: []
        });
    });
};

設置簡介:
removeSource 是否刪除源.d.ts文件
main .d.ts目錄
out 輸出文件
從新編譯 npm run build 便可在dist下生成main.d.ts文件

生成main.d.ts沒問題,可是編譯會報:
(node:38612) DeprecationWarning: Tapable.plugin is deprecated. Use new API on .hooks instead
有人知道怎麼解決,請留言!

4.使用webworker

安裝模塊 file-loader

npm i -D file-loader

在src文件夾下增長文件:
file-loader.d.ts

declare module "file-loader?name=[name].js!*" {
    const value: string;
    export = value;
}

tes.worker.ts

onmessage = function (msg) {
    console.log("webworker receive" +msg);
    postMessage('this is the response ' + msg.data);
}

修改main.ts

import { dome } from "./hello";

console.log("hello typescript + webpack + vscode!");
dome.sayWord("@@@@@@@@@");

import * as workerPath from "file-loader?name=[name].js!./test.worker";
const worker = new Worker(workerPath);
worker.addEventListener('message', message => {
    console.log(message);
});
worker.postMessage('this is a test message to the worker');

從新編譯 npm run build 便可在dist下生成test.worker.js文件
F5運行項目,可在console中看到消息交互。
圖片描述

本站公眾號
   歡迎關注本站公眾號,獲取更多信息