网站搜索

javascript - 为生产减少 node_modules 的大小


我们的部署过程耗时很长,其中一个原因是将 node_modules 文件夹传到生产服务器。

我的 Package.json 看起来像这样:

{
  "name": "coms-sass",
  "version": "0.0.1",
  "description": "Sass gulp task for COMS Service Portal",
  "main": "gulpfile.js",
  "dependencies": {
    "angular": "^1.5.5",
    "angular-sanitize": "=1.5.5",
    "angular-ui-bootstrap": "^1.3.2",
    "gridster": "^0.5.6",
    "gulp": "^3.9.0",
    "gulp-jshint": "^2.0.0",
    "gulp-sass": "^2.0.4",
    "jasmine-core": "^2.4.1",
    "jquery": "^2.2.3",
    "jquery.cookie": "^1.4.1",
    "jshint": "^2.9.1",
    "jshint-visual-studio": "^1.0.1",
    "karma": "^0.13.22",
    "karma-chrome-launcher": "^0.2.2",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma-requirejs": "^0.2.6",
    "lodash": "^4.6.1",
    "moment": "^2.13.0",
    "ng-csv": "^0.3.6",
    "requirejs": "^2.1.0",
    "bootstrap":  "=3.3.5" 
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "angular-mocks": "^1.5.5",
    "karma-jasmine": "^0.3.8",
    "karma-ng-html2js-preprocessor": "^0.2.1",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma-requirejs": "^0.2.6",
    "phantomjs": "^2.1.3",
    "phantomjs-prebuilt": "^2.1.6"
  }
}

我显然不想在生产构建中部署 karma 和 phantom。

我如何在部署时排除它们,还有没有其他方法可以减小我的 node_modules 文件夹的大小。

答案#1

npm install 有一个 --production 标志。在生产环境中,你可以安装 npm i --production,这将跳过所有 devDependencies。https://www.npmjs.org/doc/misc/npm-config.html#production

另一种可能性是使用 rollup.js 或 babel 进行“tree shaking”。在这里查看:http://www.2ality.com/2015/12/webpack-tree-shaking.html

答案#2

你考虑过只构建/编译/转译分发文件并仅部署那些文件吗?也就是说,只传输位于 'dist' 或类似目录下的内容。

看起来你正在构建一个面向浏览器的应用程序部分。对于这样的应用程序,node_modules 目录主要包含在编译期间使用的构建和测试工具——你不需要将它们传输到任何地方。不过,你需要的部分是 angular、jquery 以及类似的库,但这些 npm 包包含很多冗余内容,也不应该直接部署。

你应该创建一组仅用户浏览器所需的文件,并将这些文件传输到生产服务器。这通常是在构建过程中在'dist'目录中创建的内容。