Webpack + TypeScript --- 环境搭建
一、环境配置
1、新建项目(即新建文件夹:HelloWorld)
2、项目初始化:npm init -y
3、安装typescript
npm i typescript -g
tsc --init
4、目录结构如下:
5、配置构建工具(webpack5)
npm install webpack -D
npm install webpack-cli -D
npm install webpack-dev-server@3.11.2 -D
npm install clean-webpack-plugin -D
npm install html-webpack-plugin -D
npm install ts-loader
因为typescript是全局安装,所以要在项目运行之前进行链接
npm link typescript
5.1、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");
module.exports = (env,argv)=> {
let config = (argv.mode === "development")?devConfig : proConfig;
//合并文件
return merge(baseConfig,config);
};
5.2、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/tpl/index.html",
}),
],
};
5.3、webpack.dev.config.js
const webpack = require("webpack");
module.exports = {
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
devtools: "cheap-module-eval-source-map",
},
}),
],
};
5.4、webpack.pro.config.js
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
plugins: [
new CleanWebpackPlugin(),
],
};
6、配置文件:package.json
二、页面文件和ts文件
1、index.ts
let hello:string = "Hello TypeScript";
document.querySelectorAll(".app")[0].innerHTML = hello;
2、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="app"></div>
</body>
</html>
三、启动项目:
npm start
访问 http://localhost:8080/