【问题标题】:After compiling code with babel, property doesn't exist用 babel 编译代码后,属性不存在
【发布时间】:2018-11-20 06:44:49
【问题描述】:

我有一个位于 models/user.js 的文件,其内容如下:

import { mongoose } from '../index.js'

var userSchema = mongoose.Schema({
    email: String, // Self-explanatory
    password: String, // This will be a bcrypt hash
    name: String,
    verified: Boolean
})

export var User = mongoose.model('User', userSchema)

Babel 将其编译成 ES5,生成:

'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.User = undefined;

var _index = require('../index.js');

var userSchema = _index.mongoose.Schema({
    email: String, // Self-explanatory
    password: String, // This will be a bcrypt hash
    name: String,
    verified: Boolean
});

var User = exports.User = _index.mongoose.model('User', userSchema);

index.js,我对mongoose有这个要求

export const mongoose = require('mongoose')

然后 Babel 将其转换为

var mongoose = exports.mongoose = require('mongoose');

这一切对我来说看起来都不错,但是每当我运行我的(通过 Babel 编译的)代码时,我都会收到一个错误消息,告诉我找不到 _index.mongoose.Schema,这没有意义,因为一切看起来都像它是正确相关的。 index.js 在相对于 user.js 的正确位置

真正奇怪的是,我在创建自己的项目类型时使用了一种“项目模板”,并且一切都可以编译(使用基本相同的代码)完全正常。

有什么想法吗?

【问题讨论】:

  • 你真的不应该那样做。只需 import mongoose from 'mongoose' 在您实际需要它的地方,而不是依赖重新导出的值。编译过程将在多个地方处理相同的导入。此外,NodeJS 本身只评估“必需”模块一次,无论此类语句出现多少次。
  • @NeilLunn 这最终奏效了,谢谢:)。

标签: javascript node.js mongoose ecmascript-6 babeljs


【解决方案1】:

我无法解决最初的问题,但@NeilLunn 提供了一个很好的解决方法。无需尝试从我的 index.js 导入模块,因为 Node 只评估一个模块一次,您可以在辅助文件中导入它(与您在 index.js 中的操作相同)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2018-08-23
    • 1970-01-01
    • 2017-02-14
    相关资源
    最近更新 更多