tsconfig.json配置
ts编译改成监视模式
tsc a.ts -w (不合适)因为只能监视一个
tsc 直接全部监视 (需要有ts配置文件tsconfig.json)
tsconfig.json 是 ts编译器的配置文件,ts编译器会根据他的信息来编译。
{
"include":["./src/**/*"] ,
//需要被监视编译的文件 scr下面的全部文件
//**表示任意目录
//* 表示任意文件
"exclude" :[ //不需要被编译的ts(一般不写)
"./home/**/*"
],
"feles":[] //要被编译的文件(一般不写)
//编译器的选项
"compilerOptions":{
//定义编译后的js版本
"target" : "ES6",
//值可以为:es3,es4,es4,es5,es6,esnext,es2016-2020
//使用的模块化的规范
"module":"system",
//值可以为:none commonjs amd es2015 es2020 esnext
//使用到的库(一般不需要改,除非不是在浏览器端运行的)
"Lib":[],
//指定编译后的文件在哪里
"outDir" : "./dist",
//就是将编译后的代码合并到一个文件里
//模块化module 要用规定的类型
"outFile" : "./dist/app.js",
// js文件是否编译
"allowJs":false,
//检查js代码是否符合语法规范
"checkJs":false,
//是否移除注释
"removeComments": false,
//报错时不生成编译后的文件
"noEmitOnError": false,
//所有严格检查的开关(一般建议打开,提高代码规范)
"strict": true,
//严格模式 false默认 没有严格模式
"alwaysStrict": false,
//不允许隐式的any类型
"noImplicitAny": true,
//不允许不明确的类型的this
"noImplicitThis": true ,
//严格检查空值
"strictNullChecks": true
}
}
webpack结合ts
先初始化
cnpm init -y
先下载
cnpm i -D webpack webpack-cli typescript ts-loader
创建webpack.config.js文件
并配置
//最基本配置
//引入一个包
const path = require("path");
module.exports = {
"entry": "./1.ts",
"output": {
//指定打包文件的目录
"path": path.resolve(__dirname,"dist"),
//打包后文件的文件
"filename": "bundle.js"
},
//指定webpack打包时使用的模块
"module" :{
"rules" :[
{
//test 指定的时规则生效的文件
"test": /\.ts$/,
//要使用的loader
"use": 'ts-loader',
"exclude": /node_modules/
}
]
}
}
在配置tsconfig.json
{
"compilerOptions":{
"module":"ES5",
"target":"ES5",
"strict":true
}
}
然后再pachage.json(配置文件中)的”scripts“中添加”build":“webpack”
以上为最基本的ts配合webpack 用npm run build运行打包
添加配置
cnpm i -d html-webpack-plugin
在webpack.config.js中先引入
const HTMLWebpackPlugin = require("html-webpack-plugin");
然后在module.export中添加
第一种:
plugins: [
new HTMLWebpackPlugin(),
]
这样就会自动生成index.html
第二种:根据模板生成
在src下面创建index.html模板
plugins: [
new HTMLWebpackPlugin(options:{
template:"./scr/index.html"
}),
]
添加内置服务器
cnpm i -d webpack-dev-server
然后在package.json的 scripts中添加
“start" : "webpack serve --open chrome.exe"
然后运行直接用 npm start 不用一直dist
添加清除dist 重新生成dist
cnpm i -d clean-webpack-plugin
然后引入
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
plugins: [
new CleanWebpackPlugin(),
new HTMLWebpackPlugin(options:{
"template": "./scr/index.html"
}),
]
设置添加引用模块
在module.export下面添加
"resolve":{
"extensions": ['.ts','.js']
}
以上为最基本的
添加babel
cnpm i -d @babel/core @babel/preset-env babel-loader core-js
core-js就是低版本浏览器实现高版本语法(core-js)自己版本的
在webpack.config.js的rules的use改成数组形式(use中的loader是先加载后买你的)
"use":[
{ //配置babel
"loader": "babel-loader", //指定加载器
"options": { //设置babel
"presets": [ //设置预定义的环境
[
"@babel/preste-env", //指定环境的插件
{ //配置信息
"targets": { //要兼容的浏览器
"chrome":"88",
"ie":"11"
},
"corejs":"3", //corejs的版本
"useBuiltIns":"usage" //使用borejs的方式”usage"表示按需加载
}
]
]
}
},
'ts-loader'
],
配置打包环境(告诉webpack不使用箭头函数)
在output:{}中填写
environment:{
"arroewFunction": false
}