使用webpack打包typescript代码-01

初始化项目

npm init -y

安装依赖

# -D 表示--save-dev缩写
npm install -D webpack webpack-cli typescript ts-loader

配置webpack

项目根目录下创建webpack.config.js文件,并输入如下配置:

const path = require('path');

module.exports = {
    // 入口
    entry: './src/main.ts',
    // 输出
    output: {
        // 输出文件名
        filename: 'bundle.js',
        // 输出路径
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                // 匹配.ts文件
                test: /\.ts$/,
                // 使用ts-loader加载器打包
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    }
}

配置typescript

创建tsconfig.json配置文件,配置如下:

{
    "compilerOptions": {
        "target": "ES2015",
        "module": "ES2015",
        "strict": true
    }
}

配置打包命令

在文件package.json里添加执行命令:"build":"webpack"

  "scripts": {
    "build":"webpack"
  }

编写代码

在根目录下创建src目录,并在目录下创建main.ts文件,输入代码如下:

function sum(a: number, b: number): number {
    return a + b;
}

console.log(sum(1, 2));

打包项目

在命令行输入 npm run build执行成功

D:\ts_wp\chapter_01\coloring>npm run build

> coloring@1.0.0 build
> webpack

asset bundle.js 38 bytes [compared for emit] [minimized] (name: main)
./src/main.ts 79 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.93.0 compiled with 1 warning in 1823 ms

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值