在进行webpack打包ts的时候,配置和下载完依赖包之后,运行npm run dev报错
百度说是node_modules问题,卸载,重装还是不行
全部重来
- 建文件
public/index.html
src/main.ts
build/webpack.config.js - 给build/webpack.config.js添加如下代码
const {CleanWebpackPlugin} = require('clean-webpack-plugin')const HtmlWebpackPlugin = require('html-webpack-plugin')const path = require('path')
const isProd = process.env.NODE_ENV === ‘production’ // 是否生产环境
function resolve (dir) {
return path.resolve(__dirname, ‘..’, dir)}
module.exports = {
mode: isProd ? ‘production’ : ‘development’,
entry: {
app: ‘./src/main.ts’
},
output: {
path: resolve(‘dist’),
filename: ‘[name].[contenthash:8].js’
},
module: {
rules: [
{
test: /.tsx?$/,
use: ‘ts-loader’,
include: [resolve(‘src’)]
}
]
},
plugins: [
new CleanWebpackPlugin({
}),
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
resolve: {
extensions: [‘.ts’, ‘.tsx’, ‘.js’]
},
devtool: isProd ? ‘cheap-module-source-map’ : ‘cheap-module-eval-source-map’,
devServer: {
host: ‘localhost’, // 主机名
stats: ‘errors-only’, // 打包日志输出输出错误信息
port: 8081,
open: true
},}
```
- 终端打开根文件夹,输入npm init -y,自动生成package.json
输入tsc –init,自动生成tsconfig.json - 下载依赖
npm install -D typescript
npm install -D webpack@4.41.5 webpack-cli@3.3.10
报错—》我以为是版本问题,找了很多解决方案,unstall无数次,没用
将webpack与webpack-cli分开安装—》竟然成功了
npm install -D html-webpack-plugin
npm install -D clean-webpack-plugin
npm install -D ts-loader
npm install -D cross-env - 配置npm run dev
终于不报错了,弹出一个浏览器页面http://localhost:8081/
运行的是main.ts文件内容 - 关闭这个,重新终端打开输入npm run build
![](npm-run-dev报错解决/npm run build.png)
webpack打包ts终于成功了!!!干饭