安装Sass后编译及JSON脚本运行均提示‘Cannot find module’错误求助
Hey there, let's work through this "Cannot find module" error you're facing with Sass and your npm scripts. I’ve dealt with this exact issue a handful of times, so here are the most reliable fixes to get your setup working:
A common culprit here is installing Sass globally instead of locally. When you run npm scripts, they prioritize local dependencies over global ones by default. Let’s fix that:
- First, uninstall any global Sass installation if you have one:
npm uninstall -g sass - Then install Sass as a development dependency in your project:
npm install --save-dev sass
This puts the Sass executable in your project’s node_modules/.bin folder, where npm scripts can easily find it.
It’s easy to mess up the script path or command structure. Make sure your script points to the correct Sass executable and uses valid input/output paths. Here’s a working example:
{ "scripts": { "compile:sass": "sass src/scss/main.scss dist/css/style.css", "watch:sass": "sass --watch src/scss:dist/css" } }
Pro tip: If you still get the error, try using the full path to the Sass executable in your script to rule out path issues:
"compile:sass": "./node_modules/.bin/sass src/scss/main.scss dist/css/style.css"
Corrupted node_modules files or outdated lock files can cause module-not-found errors. Let’s do a clean reinstall:
- Delete your
node_modulesfolder:# Mac/Linux rm -rf node_modules # Windows (Command Prompt) rd /s /q node_modules - Delete your
package-lock.jsonfile - Reinstall all dependencies:
npm install
This ensures you get fresh, uncorrupted copies of Sass and all other packages.
Sass has minimum version requirements for Node.js. Old Node versions might not support the latest Sass releases. Check your current versions with:
node -v npm -v
If you’re running an outdated version (pre-16.x), upgrade to the latest LTS version of Node.js. Once upgraded, reinstall Sass to ensure compatibility.
Sometimes the "Cannot find module" message is misleading—it might be complaining about missing your input Sass files, not the Sass module itself. Double-check that the source path in your script (like src/scss/main.scss) exists and has no typos. For example, if your file is in src/styles instead of src/scss, that’ll trigger a file-not-found error that looks like a module issue.
内容的提问来源于stack exchange,提问作者Rahique

