typescript+webpack+vscode

typescript+webpack+vscode

转自https://blog.csdn.net/weixin_33831673/article/details/88711471

准备工作:
事先安装好 Node.jsvscode

项目创建

在文件夹空白处单击鼠标右键,选择 在此处打开Powershell窗口.

1.初始化项目

创建项目文件夹,名为twv。在该文件夹下运行命令 npm init,

回答一系列的问题(也可以直接回车使用默认值)后,在当前项目文件夹中会出现一个package.json的配置文件。

  1. {
  2.  "name": "ts_webpack_vscode",
  3.  "version": "1.0.0",
  4.  "description": "",
  5.  "main": "index.js",
  6.  "scripts": {
  7.             "test": "echo \"Error: no test specified\" && exit 1"
  8.  },
  9.  "author": "",
  10.  "license": "ISC"
  11.  }

2.安装所需的基本模块

Powershell窗口或者vscode中新建终端 输入指令:

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

使用vscode 打开此项目

3.添加配置文件

 

在项目根目录创建新文件(tsconfig.json),即TypeScipt的配置文件。参见(https://www.jianshu.com/p/245a796d95ff),tsconfig.json的创建方法都是在项目根目录中执行命令:

推荐方式
        npm install -g npx
        npx tsconfig.json
其它方式 
         tsc --init

 


下面是修改过的配置,简单介绍下:

sourcemap 是否生成.map文件
declaration 是否生成.d.ts文件
declarationDir .d.ts文件存放目录
exclude 编译时候忽略的文件

  1.  {
  2.    "compilerOptions": {
  3.                 "module": "es6",
  4.                "target": "es5",
  5.               "sourceMap": true,
  6.               "declaration": true,
  7.              "declarationDir": "./dist/typing",
  8.     "lib": [
  9.             "webworker",
  10.             "es6",
  11.            "es5",
  12.           "dom"
  13.          ]
  14.    ,
  15.   
  16.    "exclude": [
  17.             "node_moudles",
  18.            "dist"
  19.       ]
  20.  }

在项目根目录创建新文件(webpack.config.js),即webpack配置文件.
resolve.modules 编译搜索目录
ts-loader 编译typescript工具
简单介绍设置:
entry 项目入口(启动)
output 生成文件地址

  1.  const path = require('path');
  2.  module.exports = {
  3.  mode: 'development',
  4.  entry: './src/main.ts',
  5.  output: {
  6.  filename: 'main.js',
  7.  path: path.resolve(__dirname, 'dist')
  8.  },
  9.  module: {
  10.  rules: [
  11.  {
  12.  // For our normal typescript
  13.  test: /\.ts?$/,
  14.  use: [
  15.  {
  16.  loader: 'ts-loader'
  17.  }
  18.  ],
  19.  exclude: /(?:node_modules)/,
  20.  },
  21.  ]
  22.  },
  23.  resolve: {
  24.  modules: [
  25.  'src',
  26.  'node_modules'
  27.  ],
  28.  extensions: [
  29.  '.js',
  30.  '.ts'
  31.  ]
  32.  }
  33.  };
  34.  
     

4.写点代码

在根目录创建 src文件夹,在src文件夹下新建main.ts(即webpack 配置中入口)

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

在package.json中写入编译指令 "build"

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

在vscode终端中 或 Powershell(两者等同)输入

npm run build

编译生成mian.js 以及.d.ts文件

5.网页运行项目

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

  1.  <!DOCTYPE html>
  2.  <html lang="en">
  3.  <head>
  4.  <meta charset="UTF-8">
  5.  <title>TypeScript + Webpack 4</title>
  6.  </head>
  7.  <body>
  8.    <script src="dist/main.js"></script>
  9.  </body>
  10.  </html>

安装 webpack-dev-server 模块

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

在package.json中写入新指令 “dev”

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

在vscode终端中 或 Powershell(两者等同)输入

npm run dev

可以看到:

  1.  PS D:\Git\_web3d\ts_webpack_vscode> npm run dev
  2.   
  3.  ts_webpack_vscode@1.0.0 dev D:\Git\_web3d\ts_webpack_vscode
  4.  webpack-dev-server
  5.   
  6.  「wds」: Project is running at http://localhost:8080/
  7.  「wds」: webpack output is served from /
  8.  「wdm」: Hash: 7f042dbc150a27e0ecd3
  9.  Version: webpack 4.21.0
  10.  Time: 2396ms
  11.  Built at: 2018-10-20 20:45:23
  12.  Asset Size Chunks Chunk Names
  13.  main.js 338 KiB main [emitted] main
  14.  typing\main.d.ts 0 bytes [emitted]
  15.  Entrypoint main = main.js
  16.  
    .........

点击http://localhost:8080/即可启动浏览器打开该链接,F12-》console中看到

hello typescript + webpack + vscode!

运行项目完结

完善项目

使用中遇到的一些问题

1.自定义server

在webpack.config.js中添加 server自定义配置。好处之一多个项目就不会端口冲突。

compress 是否压缩
host localhost或 其他1.1.1.1
prot 自定义端口

  1. module.exports = {
  2.  ...,
  3.       devServer: {
  4.          hot: true,
  5.         compress: true,
  6.         host: 'localhost',
  7.         port: 8888
  8.        },
  9.  ...
  10.  }

重新启动server,即可产生新的 地址.

1.1 在vscode中 F5启动项目

在vscode中按F5,选择环境 chorme,自动生成配置文件launch.js ,修改配置中的url为server中设置的端口地址。

  1.  {
  2.  // 使用 IntelliSense 了解相关属性。
  3.  // 悬停以查看现有属性的描述。
  4.  // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
  5.  "version": "0.2.0",
  6.  "configurations": [
  7.  
  8. "type": "chrome",
  9.  "request": "launch",
  10.  
    "name": "Launch Chrome against localhost",
  11.  "url": "http://localhost:8888",
  12.  "webRoot": "${workspaceFolder}"
  13.  }
  14.  ]
  15.  }

按下F5即可chorme中启动项目.

2.生成独立的.map文件

安装source-map-loader 模块

npm i -D source-map-loader

修改webpack.config.js配置

  1.  module.exports = {
  2.  ...,
  3.   
  4.  devtool:'source-map',
  5.   
  6.  ....
  7.  }

devtool设置:

  1.  eval: 生成代码 每个模块都被eval执行,并且存在@sourceURL
  2.  cheap-eval-source-map: 转换代码(行内) 每个模块被eval执行,并且sourcemap作为eval的一个dataurl
  3.  cheap-module-eval-source-map: 原始代码(只有行内) 同样道理,但是更高的质量和更低的性能
  4.  eval-source-map: 原始代码 同样道理,但是最高的质量和最低的性能
  5.  cheap-source-map: 转换代码(行内) 生成的sourcemap没有列映射,从loaders生成的sourcemap没有被使用
  6.  cheap-module-source-map: 原始代码(只有行内) 与上面一样除了每行特点的从loader中进行映射
  7.  source-map: 原始代码 最好的sourcemap质量有完整的结果,但是会很慢

重新执行编译指令 npm run build,可以看到在dist下生成了新文件main.js.map.

3.合并.d.ts文件

添加测试代码hello.ts

  1.  export class dome
  2.  {
  3.         static sayWord(value:string)
  4.         {
  5.               console.warn("dome test world:"+value);
  6.         }
  7.  }

修改main.ts

  1. import { dome } from "./hello";
  2.   
  3.  console.log("hello typescript + webpack + vscode!");
  4.   
  5.  dome.sayWord("@@@@@@@@@");

代码结构

  1. ---src
  2.  -----hello.ts
  3.  -----main.ts

重新编译可以看到 dist/typing下有2个.d.ts文件.和.ts一一对应。

安装webpack-dts-bundle

npm i -D webpack-dts-bundle

修改webpack.config.js

  1. var rootDir = path.resolve(__dirname);
  2.  module.exports = {
  3.               .......,
  4.   
  5.               plugins: [
  6.                  new DtsBundlePlugin()
  7.              ],
  8.  ....
  9.   
  10.  };
  11.   
  12.  function DtsBundlePlugin() {}
  13.  DtsBundlePlugin.prototype.apply = function (compiler) {
  14.                    compiler.plugin('done', function () {
  15.                    var dts = require('dts-bundle');
  16.   
  17.                   dts.bundle({
  18.                           name: 'test',
  19.                           main: rootDir + '/dist/**/*.d.ts',
  20.                          out: rootDir + '/dist/main.d.ts',
  21.                         removeSource: false,
  22.                        outputAsModuleFolder: true,
  23.                       exclude:[]
  24.                   });
  25.      });
  26.  };

设置简介:
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

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

tes.worker.ts

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

修改main.ts

  1.  import { dome } from "./hello";
  2.   
  3.  console.log("hello typescript + webpack + vscode!");
  4.  dome.sayWord("@@@@@@@@@");
  5.   
  6.  import * as workerPath from "file-loader?name=[name].js!./test.worker";
  7.  const worker = new Worker(workerPath);
  8.  worker.addEventListener('message', message => {
  9.  console.log(message);
  10.  });
  11.  worker.postMessage('this is a test message to the worker');

重新编译 npm run build 即可在dist下生成test.worker.js文件
F5运行项目,可在console中看到消息交互。
图片描述

 
posted @ 2021-02-07 10:32  py2020  阅读(247)  评论(0)    收藏  举报