使用webpack打包ts步骤
简单使用
npm init -y
注:-y代表可以省去敲回车的步骤,生成的默认的package.json
- 安装依赖
- 根目录下创建webpack.config.js文件
const path = require('path')
module.exports = {
entry: './src/hello.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader',
exclude: /node_modules/
}
]
}
}
tsc --init
"build": "webpack --mode development",
npm run build
安装其他插件
- html-webpack-plugin-创建Html文件
- clean-webpack-plugin-每次打包重新清空目标文件夹
cnpm i -D clean-webpack-plugin html-webpack-plugin
live Server 实现实时更新
- 安装webpack-dev-server插件,相当于内置服务器
cnpm i -D webpack-dev-server
- 配置package.json脚本
"start": "webpack serve --open chrome.exe"
以chrome启动
安装babel以编译js语法
npm i -D @babel/core @babel/preset-env babel-loader core-js
注:@babel/present-env预先设置的环境,是什么环境就转换为什么代码;babel-loader是把babel与webpack结合的工具;core-js可以让老版本的浏览器运行新标准的js
最后附上完整的webpack.config.js代码
const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin} = require('clean-webpack-plugin')
module.exports = {
entry: './src/hello.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
environment: {
arrowFunction: false
}
},
module: {
rules: [
{
test: /\.ts$/,
use: [
{
loader: "babel-loader",
options:{
presets: [
[
"@babel/preset-env",
{
"targets":{
"chrome": "58",
"ie": "11"
},
"corejs":"3",
"useBuiltIns": "usage"
}
]
]
}
},
{
loader: "ts-loader",
}
],
exclude: /node_modules/
}
],
},
plugins: [
new CleanWebpackPlugin(),
new HTMLWebpackPlugin({
template: './index.html'
}),
],
resolve: {
extensions: [".ts", ".js"]
},
}
过程中可能出现的错误
- Requires Babel “^7.0.0-0”, but was loaded with “6.26.3”.
解决办法:
cnpm i babel-core@^7.0.0-bridge.0 @babel/core regenerator-runtime