webpack 和 ts 简单配置及使用

如何使用webpack 与 ts结合使用
新建项目 ,执行项目初始化

npm init -y

会生成

{
  "name": "tsdemo01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build":"webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^9.4.4",
    "typescript": "^5.1.6",
    "webpack": "^5.88.2",
    "webpack-cli": "^5.1.4"
  }
}

安装依赖 :
-D 开发依赖 等价于 --save-dev

npm i -D webpack webpack-cli typescript ts-loader

根目录下新建webpack.config.js,webpack的配置文件

// 引入path库 用于拼接路径
const path =  require('path')
//webpack 所有配置信息都写在module.exports中
module.exports={
	// 指定入口文件
	entry: './src/index.ts',
	// 指定打包文件所在目录
	output:{
		// 指定打包文件的目录
		path:path.resolve(__dirname,'dist'),
		//打包后的文件 出口
		filename:"bundle.js"
	},
	// 指定webpack打包时要使用的模块
	module:{
		// 指定要加载的规则
		rules:[
			{	
				//test 指定的是规则生效的文件 以ts结尾的文件
				test:/\.ts$/,
				// 要使用的loader
				use:'ts-loader',
				//要排除的文件
				exclude:/node-modules/			
			}
		]
	}
}

在根目录下 新建tsconfig.json

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

在package.json 的scripts中添加

"build":"webpack"

都配置好后,执行 npm run build
在目录下看到dist文件,就是成功拉!
执行结果

在项目中,需要在页面中引入js使用,
html-weback-plugin是自动生成html文件,并且自动引入相关资源

npm i -D html-webpack-plugin

配置的webpack.config.js

// 引入path库 用于拼接路径
const path = require('path');
// 引入html-webpack-plugin
const HTMLWebpackPlugin = require('html-webpack-plugin');

//webpack 所有配置信息都写在module.exports中
module.exports = {
  // 指定入口文件
  entry: './src/index.ts',
  // 指定打包文件所在目录
  output: {
    // 指定打包文件的目录
    path: path.resolve(__dirname, 'dist'),
    //打包后的文件 出口
    filename: 'bundle.js',
  },
  // 指定webpack打包时要使用的模块
  module: {
    // 指定要加载的规则
    rules: [
      {
        //test 指定的是规则生效的文件 以ts结尾的文件
        test: /\.ts$/,
        // 要使用的loader
        use: 'ts-loader',
        //要排除的文件
        exclude: /node-modules/,
      },
    ],
  },
  plugins: [
    new HTMLWebpackPlugin({
      title: '我是自定义title',
    }),
  ],
};

再执行 npm run build 时,目录会变更
自动生成html
如果想有个模板,可以在src下新增一个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>我是模板</title>
</head>
<body>
  <div id="box1">我是模板的div1</div>
</body>
</html>

在webpack.config.js中,把title 换为template

// 引入path库 用于拼接路径
const path = require('path');
// 引入html-webpack-plugin
const HTMLWebpackPlugin = require('html-webpack-plugin');

//webpack 所有配置信息都写在module.exports中
module.exports = {
  // 指定入口文件
  entry: './src/index.ts',
  // 指定打包文件所在目录
  output: {
    // 指定打包文件的目录
    path: path.resolve(__dirname, 'dist'),
    //打包后的文件 出口
    filename: 'bundle.js',
  },
  // 指定webpack打包时要使用的模块
  module: {
    // 指定要加载的规则
    rules: [
      {
        //test 指定的是规则生效的文件 以ts结尾的文件
        test: /\.ts$/,
        // 要使用的loader
        use: 'ts-loader',
        //要排除的文件
        exclude: /node-modules/,
      },
    ],
  },
  plugins: [
    new HTMLWebpackPlugin({
      // title: '我是自定义title',
      template: './src/index.html',
    }),
  ],
};

执行打包 npm run build 就会出现下图:
固定模板打包后文件
可使用webpack-dev-server 对代码进行实时的编译监控
下载:npm i -D webpack-dev-server
在package.json中配置scripts 中新增 “start”: “webpack serve --open”

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack serve --open"
  },

执行 npm run start
当代码修改,检查到后,页面会实时的进行更新

打包清空上一次内容:可使用 clean-webpack-plugin
写法与html-webpack-plugin相同
webpack.config.js文件:

// 引入path库 用于拼接路径
const path = require('path');
// 引入html-webpack-plugin
const HTMLWebpackPlugin = require('html-webpack-plugin');
// 引入clean插件
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

//webpack 所有配置信息都写在module.exports中
module.exports = {
  // 指定入口文件
  entry: './src/index.ts',
  // 指定打包文件所在目录
  output: {
    // 指定打包文件的目录
    path: path.resolve(__dirname, 'dist'),
    //打包后的文件 出口
    filename: 'bundle.js',
  },
  // 指定webpack打包时要使用的模块
  module: {
    // 指定要加载的规则
    rules: [
      {
        //test 指定的是规则生效的文件 以ts结尾的文件
        test: /\.ts$/,
        // 要使用的loader
        use: 'ts-loader',
        //要排除的文件
        exclude: /node-modules/,
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HTMLWebpackPlugin({
      // title: '我是自定义title',
      template: './src/index.html',
    }),
  ],
  // 设置引用模块
  resolve: {
    // 以.ts 和.js为结尾的扩展名文件可以做模板使用
    extensions: ['.ts', '.js'],
  },
};

比如src下另有一个item1.ts

export const hi = '你好';

想在index.ts引入,

import { hi } from './item1';
let a: string;
a = 'aaa';
console.log(a);
function sum(a: number, b: number): number {
  return a + b;
}
console.log(sum(211, 234));
console.log('hi----', hi);

直接引入,打印,在npm run build 时,会报错
解决方法是webpack.config.js配置下

// 设置引用模块
  resolve: {
    extensions: ['.ts', '.js'],
  }, 

写上这个就可以在ts中引入其他ts文件中的变量
再次打包 npm run build 就不会报错了
最后结果

就执行成功拉

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用webpack打包typescript文件,您需要安装以下依赖项: 1. `webpack`: 用于打包应用程序。 2. `webpack-cli`: 用于在命令行上运行webpack。 3. `ts-loader`: 用于加载typescript文件并将其转换为JavaScript。 4. `typescript`: 用于编写typescript代码。 安装这些依赖项后,您可以创建一个webpack配置文件,在此文件中指定您的入口点和输出文件。以下是一个例子: ```javascript // webpack.config.js module.exports = { entry: './src/index.ts', output: { filename: 'bundle.js', path: __dirname + '/dist' }, resolve: { extensions: ['.ts', '.js'] }, module: { rules: [ { test: /\.ts$/, loader: 'ts-loader', exclude: /node_modules/ } ] } }; ``` 在此配置中,我们指定了`entry`和`output`属性,以及`resolve`和`module`属性。`entry`指定应用程序的入口点,`output`指定打包后的文件名和输出目录。`resolve`属性用于指定要解析的文件扩展名。在这种情况下,我们使用`.ts`和`.js`扩展名。`module`属性使用`rules`属性指定将要使用的加载器。在这种情况下,我们使用`ts-loader`来加载和转换typescript文件。 现在,您可以在命令行上运行webpack,它将使用您的配置文件来打包您的应用程序。例如: ``` webpack --config webpack.config.js ``` 这将打包您的应用程序,并将输出文件保存在`dist/bundle.js`中。 注意:在运行webpack之前,您需要确保您的typescript代码是有效的,并且没有任何错误。您可以使用`tsc`命令来编译typescript代码,并查找任何错误。例如: ``` tsc src/index.ts ``` 这将编译`src/index.ts`文件,并生成一个JavaScript文件。如果有任何错误,它们将显示在命令行上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值