我写了下面的模块,但是导入的时候却不能如愿。文件(为简单起见,简称为文件)。
templates.js
'use strict';
export default class Templates {
constructor (args) {
this.files = [{
name: `${args.name}.js`,
path: 'src/',
content: ''
}];
/* code omitted */
}
};
我试图这样使用它。
index.js
import Templates from './templates'
const opts = {name: 'app'};
/* code ommited */
console.log('Templates >>', typeof Templates);
console.log('Templates >>', new Templates());
let tmpls = new Templates(opts);
console.log(tmpls.files[0].name);
但是我在控制台得到了以下的错误提示。
npm ERR! Linux 3.16.0-38-generic
npm ERR! argv "/home/wesleycoder/.nvm/versions/node/v5.1.0/bin/node" "/home/wesleycoder/.nvm/versions/node/v5.1.0/bin/npm" "init"
npm ERR! node v5.1.0
npm ERR! npm v3.3.12
npm ERR! Cannot read property 'name' of undefined
是的,这是一个 ~/.npm-init
稿子给谁问。
编辑。感谢@low_ghost的有用回复。
我想明白了,我的问题不是关于导出和导入类的问题,实际上是关于向这个类传递参数的问题,但不是关于不传递参数的问题。所以为了简洁起见,我把标题改了。
这个 console.log(new Templates())
在我的代码中,我试图解决的错误是关于实例化对象和获取文件数组的问题,但我是直接从 commander.js
库,而传来的参数对这个任务来说是 "矫枉过正 "的,所以我简化了参数,把输入从 commander.js
并将每一个都赋值在一个空对象的属性中,然后将这个对象沿着构造函数传递,这让我可以将 readline-sync
并从未通过的选项中读取输入,让脚本更厉害,在这之后都能正常工作。
如果 commander.js
有任何选项,给通过的选项没有库属性的额外权重。
编辑2:毕竟 commander.js
是没有用的,因为我不能把论据传到 npm init
命令到脚本本身。
由于在构造函数调用中没有参数,名称未定义。最好的解决方案,取决于意图,是检查name的存在和类型。
'use strict';
export default class Templates {
constructor (args) {
this.files = (args.name && typeof arg.name === "string")
? [{
name: `${args.name}.js`,
path: 'src/',
content: ''
}]
: [];
/* other code */
}
};
如果你对三元组没意见的话... 如果arg.name不存在或者不是字符串的话,这样就会返回一个空数组作为this.files。
EDIT:
或者,像madox2建议的那样,提供一个默认值。不过我会为name提供一个缺省值,而不是为整个args对象提供一个缺省值,比如。
constructor({ name = 'defaultName', ...otherArgs } = {})
这样的话,如果你调用
new Templates({ dir: 'repo' })
你仍然会有名字的默认值,如果你从字面上理解省略号,你可以从 otherArgs.dir 中得到 dir。= {}部分允许调用
new Templates()
并且仍然得到默认的名称。
构造函数 Templates
类将对象作为参数。如果你不传递它。args
参数为 undefined
而当你调用 args.name
. 试试这个。
console.log('Templates >>', new Templates({}));
或者:
console.log('Templates >>', new Templates({name: 'myName'}));
你也可以在你的构造函数中设置默认的参数值,然后在没有参数的情况下调用它。
constructor (args = {name: 'defaultName'}) {
//...