如何压缩Node.js TypeScript后端项目?Webpack配置报错求助
Node.js TypeScript后端项目压缩与webpack配置问题解决
问题背景
我想了解如何压缩Node.js TypeScript后端项目,同时当前的webpack.config.js配置存在问题,执行npm run build(配置为运行webpack)时遇到模块相关错误。
我的webpack.config.js配置:
const path = require('path'); var fs = require('fs') var nodeModules = {}; fs.readdirSync('node_modules').filter(function (x) {return ['.bin'].indexOf(x) === -1;}).forEach(function (mod){nodeModules[mod]= 'commonjs ' + mod; }); module.exports = { mode: 'development', target: 'node', entry: './src/server,ts', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, resolve: { extensions: ['.ts', '.js'], }, module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.node$/, loader: 'node-loader', }, ], }, externals: [nodeModules], devtool: 'source-map', };
遇到的错误示例:
ERROR in ./node_modules/sequelize/lib/dialects/postgres/hstore.js 2:15-35 Module not found: Error: Can't resolve 'pg-hstore' in 'C:\..\node_modules\sequelize\lib\dialects\postgres' resolve 'pg-hstore' in 'C:\..\node_modules\sequelize\lib\dialects\postgres' Parsed request is a module
问题修复与项目压缩方案
1. 解决当前模块找不到的错误
- 安装缺失依赖:pg-hstore是sequelize postgres方言的依赖,执行命令安装:
npm install pg-hstore --save - 修复entry路径笔误:配置里的
entry: './src/server,ts'应为./src/server.ts(把逗号改成点)。 - 优化externals配置:手动遍历node_modules生成externals容易出错,推荐用
webpack-node-externals自动处理node_modules外部化:- 安装依赖:
npm install webpack-node-externals --save-dev - 修改webpack配置:
const nodeExternals = require('webpack-node-externals'); // ... module.exports = { // ... externals: [nodeExternals()], // 替换原有的externals配置 // ... }
- 安装依赖:
2. 配置后端项目压缩(生产环境)
- 切换到production模式:mode设为
production,webpack会自动启用代码压缩、tree shaking等优化:module.exports = { mode: 'production', // ... } - 自定义压缩规则(可选):若需更精细控制,可配置
TerserPlugin(production模式默认已启用,以下为自定义示例):const TerserPlugin = require('terser-webpack-plugin'); module.exports = { // ... optimization: { minimizer: [ new TerserPlugin({ terserOptions: { compress: { drop_console: true, // 移除console.log drop_debugger: true, // 移除debugger }, }, }), ], }, // ... } - 优化source-map:生产环境推荐用
source-map(生成独立map文件)或hidden-source-map(不暴露map文件路径):module.exports = { // ... devtool: 'source-map', // 或 'hidden-source-map' // ... } - 启用tree shaking:确保tsconfig.json中配置
"module": "ESNext"或"CommonJS",配合production模式自动移除未使用的代码。
内容的提问来源于stack exchange,提问作者SelloBello106
相关产品推荐
相关产品推荐

