没有 node_modules 来自 netlify 部署

No node_modules from netlify deploy

我已经使用 Netlify 和 git 存储库进行了持续部署设置,但到目前为止,无论我做什么,Netlify 都没有 npm-installing 任何东西。当我下载部署的 zip 时,没有 node_modules 文件夹,我的站点无法访问 node_modules,它就是不存在。我从一个随机的 npm 包 (lodash) 开始尝试安装它,但到目前为止我一无所获。

Netlify 说它会自动运行 npm install。我试过没有构建命令,我尝试添加 npm install 作为构建命令,但都没有结果。

package.json:

{
  "name": "netlify-test",
  "version": "1.0.0",
  "description": "stuff",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/electrovir/netlify-test.git"
  },
  "author": "electrovir",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/electrovir/netlify-test/issues"
  },
  "homepage": "https://github.com/electrovir/netlify-test#readme",
  "dependencies": {
    "lodash": "^4.17.11"
  }
}

HTML:

<!doctype html>
<html>

<head>
    <title>
        hi
    </title>
    <script src="node_modules/lodash/_apply.js"></script>
</head>

<body>
    Why can't this find node_modules??
</body>

</html>

如果有 node_modules 就奇怪了。 Netlify 的持续部署会 运行 npm install 为你安装,当且仅当你的存储库的根目录中有一个 package.json(或者如果你在 base 目录中设置一个 netlify.toml. However, it also uses a custom npm directory that is outside of the deployment directory (see how it is setup here: https://github.com/netlify/build-image/blob/master/run-build-functions.sh#L34), since deploying your node_modules shouldn't be needed for a static site 在浏览时 - 仅在构建时。

Netlify 部署的预期路径是:

  1. 您已将依赖管理器配置检查到您的 git 存储库的根目录(如果 UI 或 toml 文件中未设置 base 目录)或者在 base 目录中(如果已设置)。这可能是 Gemfile.lockpackage.jsonyarn.lockrequirements.txt 中的 any/all,如 this article about the build settings at Netlify
  2. 中所述
  3. 您没有将 node_modules 存储在存储库中。其中许多将特定于构建环境的体系结构——并且您的本地计算机几乎肯定与 Netlify 的不同。你会想要那些在构建时生成的。
  4. 您的构建旨在在 BUILD 期间使用这些模块。所以你使用例如 dotenv to read your .env file while building, or you use gulp-cli 来处理你的 Gulpfile.js
  5. 您的构建完成,并且您在构建过程中使用了所有模块来生成独立 html/js/css/images,因此您已经完成了它们 - 您的静态 html 和其他资产已在您的publish 目录,构建过程有意 而不是 放置您的节点模块,因此它们不会被部署。您的静态网站在 运行 时不需要这些模块,因此在其中部署(数千!)文件效率不高,也不需要。

您可能遇到需要 some/one 的情况 - 例如a function 或者即使在静态站点上,您也可能需要其中之一的文件 - 没关系,请随意将其显式复制到发布目录中。但这不是常态:)

花了一段时间才弄明白,但我发现 Netlify 确实 npm install 进入你的 repo root 或 Base 目录 当你有一个 package.json 时。这可以通过将 Build 命令 更改为类似 ls 并读取部署控制台输出(将列出一个 node_modules 文件夹)来查看。

但是,在 运行 构建命令 之后和部署之前的某个时刻,此 node_modules 被删除。因此,如果您使用类似于以下内容的 Build 命令node_modules 可以复制到您的 Publish 目录

rm -rf dist && mkdir dist && rsync -rv * dist --exclude ./dist

这会将 基本目录 的内容复制到 dist 中,我已将其设置为我的 发布目录 ,忽略 ./dist本身(不能复制到自身)。如果将其作为 npm 脚本添加到 package.json 中,并为您的 Build 命令 .

添加 npm run <script name>,那就更好了

注意基目录构建命令发布目录都在Deploys > Deploy settingsSettings > Build & deploy 在 Netlify 中。

感谢 lastmjs 帮助解决这个问题。