helloTypeScript
function greeter(person: string) {
return `hello${person}`
}
const user = 'typeScript'
console.log(greeter(user))
var message = 'helloTypeScript';
console.log(message);
tip
在文件夹下新建一个tsconfig.json
文件,能解决vscode
代码爆红异常
高效的编写ts
注意先用npm init -y
初始化一个仓库
一.搭建webpack环境
npm
安装依赖
npm i webpack webpack-cli -D
npm
安装热更新模块
npm i webpack-dev-server -D
npm
安装插件
detail see
http://www.smartxy.cc/blogs/category/webpack/webpack.html#html-webpack-plugin
npm install --save-dev html-webpack-plugin
npm
安装相关loader
npm i ts-loader typescript -D
初始化ts
配置文件
tsc --init
根目录新建webpack.config.js
文件该文件为webpack
的配置文件
配置内容
const path = require('path')
// 插件
// html自动生成插件
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// 打包的入口文件
entry: './src/main.ts',
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
},
extensions: ['.ts', '.js', '.cjs', '.json'],
},
output: {
// 生成的js名字
filename: 'js/[name].[contenthash].js',
// 输出的文件目录
path: path.resolve(__dirname, 'dist'),
// 每次打包清除dist文件夹下面的内容
clean: true,
},
// 开发环境 | 生产环境
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
// 以哪个html为模板
template: './src/index.html',
// 生成的html文件名
filename: 'index.html',
// 脚本等相关文件注入到哪里
inject: 'body'
}),
],
module: {
// 配置规则
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
}
]
}
}
修改package.json
部分内容
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve": "webpack server"
},
运行npm run serve
即可看到效果
二.使用ts-node
npm
安装依赖
npm i ts-node -g
npm
安装ts-node
需要的依赖包
npm i tslib @types/node -g
运行ts文件
ts-node 你的ts文件