我正在学习通过创建一个会话检查函数sessionFn
来创建npm包,它会在会话到期前1分钟弹出一个模态。
该函数在主应用程序(nuxtJS应用程序)上按预期工作,但当我将其用作npm模块时,我必须将moment
作为参数传递,即使moment
被列为依赖项并在模块上导入。
我错过了一些东西,为什么我的模块没有发现时刻?我想使用像sessionFn(this, to.path);
这样的模块而不是sessionFn(this, to.path, moment);
当我没有通过时,时刻是未定义的
包文件
的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);
}
}
...
}
您不需要导入并将时间传递到函数中,因为您要在函数文件中导入它。您甚至没有在函数中使用传递的参数。所以你可以安全地通过它。你也没有使用传递to.path
的第二个参数,所以你也可以省略它。
作为建议你应该安装和使用eslint,它会捕获这些东西。例如,您可以使用create nuxt app设置带有eslint的nuxt项目。
esm 3.21-3.22中还有一个错误,它阻止commonjs和es6导入一起工作https://github.com/standard-things/esm/issues/773。当一个新的esm将被释放时,应该修复它
尝试通过moment
而不是依赖来使npm i moment --save-dev
成为devDependancy。
这样,只有在开发包时(意味着开发项目时)才需要时刻,而不是在使用它时。
希望它能解决你的问题