前端工程化Vue使用Node.js设置国内高速npm镜像源(踩坑记录版)
    		       		warning:
    		            这篇文章距离上次修改已过449天,其中的内容可能已经有所变动。
    		        
        		                
                
// 使用Node.js脚本设置中国区的npm镜像
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
 
// 设置npm的中国区镜像
const setNpmMirror = () => {
  try {
    execSync('npm config set registry https://registry.npm.taobao.org', { stdio: 'inherit' });
    console.log('设置npm镜像源成功!');
  } catch (error) {
    console.error('设置npm镜像源失败:', error);
  }
};
 
// 创建或更新.npmrc文件
const updateNpmrcFile = () => {
  const npmrcPath = path.join(process.cwd(), '.npmrc');
  try {
    fs.writeFileSync(npmrcPath, 'registry=https://registry.npm.taobao.org\n', 'utf-8');
    console.log('更新.npmrc文件成功!');
  } catch (error) {
    console.error('更新.npmrc文件失败:', error);
  }
};
 
// 主函数
const main = () => {
  setNpmMirror();
  updateNpmrcFile();
};
 
main();这段代码使用Node.js的child_process模块执行命令行指令,并且使用fs模块来创建或更新.npmrc配置文件。它提供了一种自动化设置npm镜像源的方法,并且可以避免手动操作带来的错误风险。
评论已关闭