hello TypeScript env

全局安装typescript

npm i -g typescript

全局安装ts有利于方便的使用
调用npx tsc -h可以查看tsc的帮助选项,选项中的大部分功能都可以通过配置文件设置,配置文件可以通过命令生成

npx tsc --init
// 成功后输出
// message TS6071: Successfully created a tsconfig.json file.

此时可通过npx tsc 来进行.ts文件的编译

安装webpack

npm i -D webpack webpack-cli webpack-dev-server
设置基础配置webpack.base.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'app.js'
    },
    resolve: {
        extensions: ['.js', '.ts', '.tsx']
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/i,
                use: [{
                    loader: 'ts-loader'
                }],
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/template/index.html'
        })
    ]
}

安装依赖

npm i ts-loader typescript html-webpack-plugin -D

在指定目录创建html模板
./src/template/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TypeScript in Action</title>
</head>
<body>
    <div class="app"></div>
</body>
</html>
配置开发环境webpack.dev.config.js
module.exports = {
    devtool: 'cheap-module-eval-source-map'
}

以上配置的source-map会忽略列信息,定位时会定位到ts源码

配置生产环境webpack.pro.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    plugins: [
        new CleanWebpackPlugin()
    ]
}

添加依赖

npm i -D clean-webpack-plugin

用于成功构建后清理构建目录

配置全局webpack

webpack.config.js

const merge = require('webpack-merge');
const baseConfig = require('./webpack.base.config');
const devConfig = require('./webpack.dev.config');
const proConfig = require('./webpack.pro.config');

const config = process.NODE_ENV === 'development' ? devConfig : proConfig;

module.exports = merge(baseConfig, config);

安装依赖

npm i -D webpack-merge

用于合并webpack配置

添加package脚本
"scripts": {
    "start": "webpack-dev-server --mode=development --config ./build/webpack.config.js",
    "build": "webpack --mode=production --config ./build/webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

脚本指定了当前环境的mode和使用的构建工具

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值