使用Webpack打包Typescript

1. 初始化项目

# 创建文件夹
mkdir part3
# 进入文件夹
cd part3
# 使用npm初始化
npm init
# 加载相关依赖 ts-loader用于在webpack中编译ts文件
cnpm i -D webpack webpack-cli typescript ts-loader

2. 创建webpack配置

创建一个webpack.config.js文件

// 引入一个包
const path = require('path')
// webpack中的所有配置信息否应该卸载 module.exports中
module.exports = {
    // 指定入口文件
    entry:"./src/index.ts",
    // 指定打包文件输出的目录
    output: {
        // 相当于 ./dist
        path: path.resolve(__dirname,'dist'),
        // 打包后的文件
        filename:"bundle.js"
    },
    // 指定webpack打包是要使用的模块
    module:{
        // 指定加载的规则
        rules: [
            {
                // test 指定的是规则生效的文件 ,匹配所有以 .ts结尾的文件
                test: /\.ts$/,
                // 指定loader解析
                use: 'ts-loader',
                // 指定要派出的文件
                exclude: /node-modules/
            }
        ]
    }
}

3. 创建ts配置文件

使用webstorm的话直接用它新建的就行了

{
  "compilerOptions": {
    "module": "ES6",
    "target": "ES6",
    "sourceMap": false,
    "strict": true
  },
  "exclude": [
    "node_modules"
  ]
}

4. 运行打包

  1. src目录下创建index.ts
function sum(firstNum: number,lastNum: number) :number{
    return firstNum + lastNum
}
  1. 修改package.json,添加打包配置
{
  "name": "part3",
  "version": "1.0.0",
  "description": "使用webpack整合typescript打包",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    // 在这里添加build参数,使用webpack打包  
    "build": "webpack"
  },
  "author": "eleven",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^9.4.1",
    "typescript": "^4.8.4",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"
  }
}
  1. 运行打包
# 运行打包
npm run build
# 打包之后会出现下列提示信息
> [email protected] build E:\study\code\typescript\part3
> webpack

asset bundle.js 0 bytes [emitted] [minimized] (name: main)
./src/index.ts 15 bytes [built] [code generated]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

webpack 5.74.0 compiled with 1 warning in 1061 ms
  1. 如果出现了跟上边的提示mode错误,可以修改一下打包参数
{
    "scripts": {
    	"build": "webpack --mode production"    
    }
}
  1. 打包完成之后会在项目目录下生成dist/bundle.js

5. 优化打包

  1. 添加webpack插件,可以自动的生成html文件
cnpm i -D html-webpack-plugin
  1. 修改webpack.config.js
// 引入html插件
const HTMLWebpackPlugin = require('html-webpack-plugin')
// 在 module.exports 中添加插件
module.exports = {
    plugins:[
        new HTMLWebpackPlugin()
    ]
}
  1. 重新执行打包命令
cnpm run build
  1. 修改生成的html的titile
plugins:[
    new HTMLWebpackPlugin({
        // 这种情况只能指定生成的html的那个title
        title: '这是自顶一个的title'
    })
]
  1. 设置生成的模板,让后续生成的按照这个模板文件生成,在src下创建模板文件
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Lesscodingtitle>
    <link rel="icon" href="https://lesscoding.net/img/icon_2.da28b7db.png">
head>
<body>

body>
html>
  1. 修改webpack.config.js
plugins:[
    new HTMLWebpack({
        template:'./src/template.html'
    })
]
  1. 添加webpack开发服务器,自动打开浏览器
npm install -D webpack-dev-server
  1. 修改package.json
{
    "script":{
        // 使用chrome打开
        // 这里如果提示Cannot GET /chrome 就把chrome.exe删掉
        // 如果提示mode xxx 则改成webpack server --open --mode production
        "start":"webpack serve --open chrome.exe"
    }
}
  1. 运行
npm start
  1. 添加一个clean-webpack-plugin,打包时删除旧的文件
npm i -D clean-wepack-plugin
  1. 修改webpack-config.json
// 引入clean插件
const CLeanWebpackPlugin = require('clean-webpack-plugin')
module.exports = {
    plugins:[
        new CleanWebpackPlugin()
    ],
    // 用来设置引用的模块
    resolve: {
        // 解析的后缀
        extensions: ['.ts','.js']
    }
}

6. 使用babel相关兼容

  1. 添加相关npm依赖
# 安装@babel/core
# 安装@babel/preset-env 预设浏览器版本
# 安装 babel-loader 加载器
# 安装core-js 兼容不同浏览器js
cnpm i -D @babel/core @babel/preset-env babel-loader core-js
  1. 修改webpack.config.js,添加相关内容
module.exports = {
    output: {
        // 指定不适用 箭头函数包含,兼容ie浏览器
        environment:{
            arrowFunction: false
        }
    },
    // 指定webpack打包是要使用的模块
    module:{
        // 指定加载的规则
        rules: [
            {
                // test 指定的是规则生效的文件 ,匹配所有以 .ts结尾的文件
                test: /\.ts$/,
                // 将use改为数组 指定loader加载器,从后往前执行
                use: [
                    // 相较于直接写加载器名称,这种配置更为全面
                    {
                        //指定加载器
                        loader:'babel-loader',
                        // 配置babel
                        options:{
                            presets:[
                                [
                                    //指定环境插件
                                    "@babel/preset-env",
                                    //配置信息
                                    {
                                        // 运行到的浏览器的版本
                                        targets:{
                                            "chrome":"88",
                                            // ie 不支持let const写上这个肯定所有浏览器都可以执行
                                            "ie":"8"
                                        },
                                        // 看 package.json中引入的corejs的大版本
                                        "corejs":"3",
                                        // 使用 corejs 的方法 "usage"表示按需加载
                                        "useBuiltIns":"usage"
                                    }
                                ]
                            ]
                        }
                    },
                    'ts-loader'
                ],
                // 指定要派出的文件
                exclude: /node-modules/
            }
        ]
    }
}

7. 完整文件

1. package.json

  1. 初始化的时候添加了 webpack webpack-cli typescript ts-loader 用来加载webpack与ts相关
  2. 添加 html-webpack-plugin 、clean-webpack-plugin、webpack-dev-server插件用来简化运行启动
  3. 添加
{
  "name": "part3",
  "version": "1.0.0",
  "description": "使用webpack整合typescript打包",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production",
    "start": "webpack serve --open  --mode production "
  },
  "author": "eleven",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.19.3",
    "@babel/preset-env": "^7.19.4",
    "babel-loader": "^8.2.5",
    "clean-webpack-plugin": "^4.0.0",
    "core-js": "^3.25.5",
    "html-webpack-plugin": "^5.5.0",
    "ts-loader": "^9.4.1",
    "typescript": "^4.8.4",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  }
}

2. tsconfig.json

{
  "compilerOptions": {
    "module": "ES6",
    "target": "ES6",
    "sourceMap": false,
    "strict": true
  },
  "exclude": [
    "node_modules"
  ]
}

3. webpack.config.js

// 引入一个包
const path = require('path')
// 引入 html插件
const HTMLWebpackPlugin = require('html-webpack-plugin')
// 引入清除插件
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
// webpack中的所有配置信息否应该卸载 module.exports中
module.exports = {
    // 指定入口文件
    entry:"./src/index.ts",
    // 指定打包文件输出的目录
    output: {
        // 相当于 ./dist
        path: path.resolve(__dirname,'dist'),
        // 打包后的文件
        filename:"bundle.js",
        // 指定不使用 箭头函数包含 兼容ie浏览器的时候使用
        environment:{
            arrowFunction: false
        }
    },
    // 指定webpack打包是要使用的模块
    module:{
        // 指定加载的规则
        rules: [
            {
                // test 指定的是规则生效的文件 ,匹配所有以 .ts结尾的文件
                test: /\.ts$/,
                // 指定loader加载器,改为数组,从后往前顺序执行
                use: [
                	// 使用这种配置更为的详细
                    {
                        //指定加载器
                        loader:'babel-loader',
                        // 配置babel
                        options:{
                            presets:[
                                [
                                    //指定环境插件
                                    "@babel/preset-env",
                                    //配置信息
                                    {
                                        // 运行到的浏览器的版本
                                        targets:{
                                            "chrome":"88",
                                            // ie 不支持let const写上这个肯定所有浏览器都可以执行
                                            "ie":"8"
                                        },
                                        // 看 package.json中引入的corejs的大版本
                                        "corejs":"3",
                                        // 使用 corejs 的方法 "usage"表示按需加载
                                        "useBuiltIns":"usage"
                                    }
                                ]
                            ]
                        }
                    },
                    'ts-loader'
                ],
                // 指定要派出的文件
                exclude: /node-modules/
            }
        ]
    },
    // 配置webpack插件
    plugins:[
        new HTMLWebpackPlugin({
            // title: '自动生成的Title'
            template:'./src/template.html'
        }),
        new CleanWebpackPlugin()
    ],
    // 用来设置引用的模块
    resolve: {
        extensions: ['.ts','.js']
    }
}

你可能感兴趣的:(前端笔记,webpack,typescript,javascript)