如何使用 npm 包依赖

How to use npm package dependency

我正在学习通过创建一个会话检查函数来创建 npm 包 sessionFn,它将在会话过期前 1 分钟弹出一个模式。

该函数在主应用程序(nuxtJS 应用程序)上按预期工作,但是当我将它用作 npm 模块时,即使列出了 moment,我也必须将 moment 作为参数传递作为依赖项并导入到模块中。

我遗漏了一些东西,为什么我的模块没有启动?我想使用 sessionFn(this, to.path); 之类的模块而不是 sessionFn(this, to.path, moment); moment is undefined when I don't pass it

打包文件

package.json

{
  "name": "hello-stratech",
  "version": "1.0.17",
  "description": "Hello Stratech",
  "main": "index.js",
  "keywords": [
    "npm",
    "hello",
    "stratech"
  ],
  "author": "Simo Mafuxwana",
  "license": "ISC",
  "dependencies": {
    "moment": "^2.22.2"
  }
}

index.js(主js文件)

import moment from "moment";

module.exports = {
  greeting(name) {
    alert("Hello.. " + name);
  },
  department(dev) {
    ...
  },
  sessionFn(context) {
    const exp = context.$store.state.session.exp;
    let userSystemTime = new Date();
        userSystemTime = moment.utc(userSystemTime)

    const diff = moment(userSystemTime).diff(moment(exp), 'minutes');
    if (diff = 1) {
      // open modal
    }
  }
}

用法

这就是我在主应用程序中使用包的方式

import moment from 'moment';
import { sessionFn } from "hello-stratech";

export default {
  ...
  watch: {
    $route(to) {
      sessionFn(this, to.path, moment);
    }
  }
  ...
}

尝试通过 npm i moment --save-dev 而不是依赖将 moment 作为 devDependancy。

只有在开发包时(意味着您正在开发项目时)才需要这种方式,但在使用时不需要。

希望它能解决您的问题

for more depth knowledge

您不需要导入 moment 并将其传递到您的函数中,因为您正在将它导入到您的函数文件中。您甚至没有在函数中使用传递的参数。所以你可以安全地不通过它。您也没有使用您传递的第二个参数 to.path,因此您也可以省略它。

作为建议,您应该安装并使用 eslint,它会捕获此类内容。例如,您可以使用 create nuxt app 使用 eslint 设置 nuxt 项目。

esm 3.21-3.22 中还有一个错误阻止 commonjs 和 es6 导入一起工作https://github.com/standard-things/esm/issues/773。发布新的 esm 时应该会解决这个问题