天天看点

webpack + TypeScript搭建工程

工程搭建

环境:浏览器 + 模块化

webpack: 构建工具,更据人口文件找寻依赖关系,打包

安装

npm i webpack webpack-cli -D

安装插件

npm i -D html-webpack-plugin clean-webpack-plugin webpack-dev-server

webpack.config.js配置

devServer: {
    open: true,
    port: 8000
},
           

配置命令

"scripts": {
  "start": "npx webpack-dev-server --mode=development",
  "build": "npx webpack --mode=production"
},
           

package.json

{
  "name": "teris-game",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npx webpack-dev-server --mode=development",
    "build": "npx webpack --mode=production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^4.0.0",
    "ts-loader": "^9.2.5",
    "typescript": "^4.4.3",
    "webpack": "^5.52.1",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "^4.2.1",
    "html-webpack-plugin": "^5.3.2"
  },
  "dependencies": {}
}
           

配置TS

安装 ts相应loader ts-loader(官方) 或 awsome-typescript-loader

和对应的依赖 typescript

npm i -D ts-loader typescript

webpack.config.js配置

rules: [{
    test: /\.ts$/,
    loader: "ts-loader"
}]
           

生成 ts配置文件 tsconfig.json

tsc --init

配置详情

{
  "include": [
    "./src"
  ], 
  "compilerOptions": {
    "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
    "module": "ESNext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "lib": ["ES2016", "DOM"],                                   /* Specify library files to be included in the  */
    "sourceMap": true,                              /* Generates corresponding '.map' file. */
    "removeComments": true,                         /* Do not emit comments to output. 移除注释 */
    "isolatedModules": true,                        /* 要求每个ts文件读书一个模块 Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    "moduleResolution": "node",                  /* 模块解析方式 Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "esModuleInterop": true, /* 使用es6模块化方式与其他模块化方式交互 Enables emit interoperability between CommonJS 
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
  }
}
           

此时,写一个模块

// myModule.ts
export const a = 1

// index.ts
import {a} from './myModule'
console.log('a',a)
export default {}
           

会抛出错误

Can't resolve './myModule' in 'xxx\teris-game\src' resolve './myModule'

让webpack也读取ts文件, 让webpack多解析一个 .ts 文件

resolve: {
    extensions: ['.ts', '.js']
}
           

继续阅读