【发布时间】:2017-02-04 05:18:20
【问题描述】:
更新
根据 Epiqueras 的回答,我查看了我是如何处理导入的。首先,/models/index.js 正在导出命名导出。代码如下:
'use strict';
import { readdirSync } from 'fs'
import {
basename,
extname,
resolve
} from 'path';
//
// Using module.exports here as a bit of a hack
// to allow for member imports in the form of
// import { Constructor } from "~/models"
module.exports = readdirSync(__dirname) // Get contents of current directory
.filter(f => f !== 'index.js') // Exclude the index file
.map(f => resolve(__dirname, f)) // Resolve the complete module file path
.map(f => require(f).default) // Require the module
.reduce((prev, next) => { // Reduce the array of modules to a hash of Module.name = Module
prev[next.name] = next;
return prev;
}, {});
我是从requireindex 项目中得出的,该项目对我不起作用(无疑是用户错误)。后来我发现,如果我直接导入类,即import Patron from '../models/patron',那么一切都会按预期工作。
此时,我的项目中有五个其他模型都可以使用上面的代码正常导出。 Patron 是唯一没有的。如原始问题所述,如果我将名称更改为其他名称,则上面的代码会毫无问题地导出该新名称。
谢天谢地,我现在有一个解决方法。希望我能弄清楚为什么 Patron 这个名字会让人窒息。
原始问题
我用 JavaScript 写了一个简单的类:
'use strict'
export default class Patron {
constructor(props) {
this.props = props;
}
create() {
// In my actual code I make a network call,
// simplified this just to see if anyone can get it to return a promise
return Promise.resolve(this);
}
}
为了完整起见,下面是我如何使用构造函数的示例:
'use strict'
import { Router } from 'express';
import { Patron } from '../models';
const PatronRouter = Router();
PatronRouter.post('/patrons', (req, res) => {
let patron = new Patron({ name: 'John Doe' });
let promise = patron.create().then(response => res.send(response);
}
export PatronRouter;
这是我的经历:
-
Patron是一个有效的构造函数,初始化实例没有错误 -
patron是Patron的一个实例 -
patron.props是undefinded -
patron.create作为实例方法存在 -
patron.create返回undefined
这对我来说完全没有意义:如果我更改类的名称,一切正常。我不明白名称 Patron 是在哪里/如何/为什么导致问题的?
其他几点说明:
- 运行节点 (6.9.2)
- Express(最新)应用程序的一部分,尝试从
Router执行此代码 - 在启用
es2015预设的情况下使用 Babel 6
想法?
【问题讨论】:
-
你能展示事物的导入方面吗?你在任何地方还有其他
Patron符号吗?您是否查看了 Babel 生成的代码以确切了解生成的代码是什么样的? -
您的代码似乎有效,但您的经验错误:
patron.props = defined和patron.create => Promise.<Patron>。可能在您使用此代码的某个地方出错了。 -
请注意,如果您进行 ajax 调用,则不应返回
Promise.resolve()但实际上将该调用包装到new Promise((accept,reject)=> {Your code here}) -
@jfriend00 扩展了导入/使用示例。我在任何地方都没有找到任何其他
Patron符号,而且我不完全确定我知道如何查看 babel 生成的代码。此时,我只是通过npm start学习/调试,启动脚本为nodemon index.js --exec babel-node -
对
new Patron的调用不太可能成功,因为Patron作为默认导出导出,但随后作为命名导出导入,这意味着它可能未定义。
标签: javascript ecmascript-6 es6-class