WSL2 Ubuntu环境执行npm install遇node-sass编译失败(Python缺失)求助
Hey there, I’ve hit this exact problem before when setting up older Node.js projects in WSL2 Ubuntu—let’s get this sorted out quickly!
What’s Causing the Error?
Looking at your log, the core issue is that node-gyp (the tool node-sass uses to compile native code) can’t find a Python executable. The version of node-gyp bundled with your node-sass (v3.8.0) still expects Python 2, but WSL2 Ubuntu doesn’t come with Python pre-installed. On top of that, your Node.js version (v17.0.1) is quite new, and older node-sass versions don’t support it—this adds another layer of compatibility issues.
Solutions to Try
1. Quick Fix: Install Python 2 & Build Dependencies
If you need to get node-sass working right away without changing packages:
- First, install Python 2 and essential build tools for node-gyp:
sudo apt update && sudo apt install python2 make g++ -y - Run
npm installagain, telling node-gyp to use Python 2:PYTHON=python2 npm install - To make this permanent (so you don’t have to set the env var every time), add this line to your shell config (
~/.bashrcor~/.zshrc):echo 'export PYTHON=python2' >> ~/.bashrc && source ~/.bashrc
2. Long-Term Fix: Switch to Dart Sass (Recommended)
Node-sass is deprecated—the official replacement is Dart Sass (published as sass on npm), which doesn’t require native compilation with node-gyp at all. This will eliminate future compatibility issues with newer Node versions:
- Uninstall node-sass:
npm uninstall node-sass - Install Dart Sass:
npm install sass - Update any build configs (like Webpack, Gulp, or Vue CLI) that reference
node-sassto usesassinstead—most tools will work seamlessly with the replacement.
3. Match Node.js Version to Node-Sass Compatibility
If you must keep using node-sass, you’ll need to switch to a Node.js version that’s supported by your node-sass version. Node v17 isn’t compatible with older node-sass releases, so use nvm to switch to a supported version like Node v16:
nvm install 16 && nvm use 16
Then follow the steps in Solution 1 to install Python 2 and build tools.
Final Recommendation
I’d strongly suggest going with Solution 2 (switching to Dart Sass) since node-sass is no longer maintained, and it’ll save you from dealing with native compilation headaches in the future.
内容的提问来源于stack exchange,提问作者ImBIOS

