Webpack无法识别Node的process模块,Node+TS+Webpack项目构建遇阻
process Module for Node.js + TypeScript Projects Hey there! It’s totally normal to feel overwhelmed diving back into JavaScript after a decade—this modern ecosystem does have a lot of moving parts. Let’s fix that process module issue with Webpack real quick.
First, let’s break down why this is happening: By default, Webpack is optimized for browser environments, so it doesn’t automatically recognize Node.js core modules like process unless you explicitly tell it to target Node.js. Your tsc command works because your TypeScript config is set up for Node, but Webpack’s default settings are overriding that.
Here’s how to fix it step by step:
1. Set Webpack’s target to node
In your Webpack config file (usually webpack.config.js or webpack.config.ts), add or update the target property to 'node'. This tells Webpack to bundle for Node.js instead of the browser, so it’ll preserve references to Node core modules:
module.exports = { target: 'node', // This is the critical line entry: './src/run_task.ts', // ... rest of your config (module rules, output, etc.) };
2. Align TypeScript & Webpack Module Resolution
Double-check that your server.tsconfig.json has settings that play nice with Node.js:
- Set
moduletoCommonJS(orESNextif you’re using ESM, but CommonJS is safer for out-of-the-box Node compatibility) - Ensure
moduleResolutionis set tonode - Verify
targetis set to a Node-compatible version (likeES2020or higher)
Example snippet from server.tsconfig.json:
{ "compilerOptions": { "target": "ES2020", "module": "CommonJS", "moduleResolution": "node", "outDir": "./dist", // ... other options } }
3. Handle process.env Variables (If Needed)
If your code uses process.env variables, you’ll want to inject them explicitly with Webpack’s DefinePlugin. Add this to your Webpack config’s plugins array:
const webpack = require('webpack'); module.exports = { // ... other config plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'), // Add other env vars your project needs here }), ], };
4. Verify Your TS Loader Setup
Make sure your Webpack config is processing TypeScript files correctly with ts-loader or babel-loader. For ts-loader, your module rules should look like this:
module.exports = { // ... other config module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, options: { configFile: 'server.tsconfig.json', // Point to your custom TS config }, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, };
After making these changes, run your Webpack build again—it should recognize the process module without issues now.
内容的提问来源于stack exchange,提问作者Jehjoa

