【问题标题】:export/import javascript class like module node into electron with webpack使用 webpack 将 javascript 类(如模块节点)导出/导入到电子中
【发布时间】:2019-05-09 13:23:54
【问题描述】:

在基本的 Electon-vue 应用程序的上下文中,我想创建自己的 javascript 类并将其用于主进程或渲染器或 vue 组件。

我创建了 JS 类,但我从来没有找到导出我的类的好方法。

所有在网络上编写导入/导出模块的可能性都由相同的错误完成:未定义的导出

"use strict"

import fs from 'fs'
import typeorm from 'typeorm'
import Public from './../entity/Public'

class ConnectionManager
{
    constructor(){}

    getConnection(type, name, options) {

    }
}

module.exports = ConnectionManager

但是看起来其他 js 文件可以像 vue-router js 一样完美地工作,用于路由到 vue.js 应用程序:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: require('@/components/Home').default
    }
]
})

我用 Webpack 和 libraryTarget 打包我的代码输出是:commonjs2

我似乎将 babel-loader 与 webpack 一起使用

节点版本:10.13.0

电子:3.0.10

通天塔:6

编辑:

我试试这个语法类 js 文件:

"use strict"

import * as fs from 'fs'
import * as typeorm from 'typeorm'
import {Public} from './../entity/Public'

export default class ConnectionManager
{
    constructor(){}

    getConnection(type, name, options) {

    }
}

使用此导入语法:

import ConnectionManager from './../service/connectionManager'

但是当我在电子中执行代码时出现此错误:

未捕获的类型错误: _service_connectionManager__WEBPACK_IMPORTED_MODULE_8__.default.getConnection 不是函数

我在控制台记录了这个服务类“ConnectionManager”,我得到了这个结果(所以它确实存在):

ƒ ConnectionManager() {
    babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ConnectionManager);
}

貌似最终的js模块webpack包含ConnectionManager类

【问题讨论】:

  • 你如何使用这个类?看起来您没有创建实例。

标签: node.js webpack electron


【解决方案1】:

看来你把 commonjs 模块和 ES 模块混用的方式不对。

有很多模块(包括内置节点)没有default export。要import 这样的模块,您需要在导入语句中使用* as moduleAlias{ exportedField }。尝试用这种方式重写你的代码:

import * as fs from 'fs'
import * as typeorm from 'typeorm'
import { Public } from '../entity/Public'

export default class ConnectionManager
{
    constructor(){}

    getConnection(type, name, options) {

    }
}

因为这个类是exported作为默认值,你可以使用下面的构造将import它作为默认字段,其中ConnectionManager是当前作用域的别名:

import ConnectionManager from '../service/connectionManager'

【讨论】:

  • 这个文件似乎写得很好,但无法将它导入其他文件。 Webpack 错误,找不到函数。但是console.log这个类好像不错。
  • 如何导入这个类?
  • 从 './../service/connectionManager' 导入 * 作为 ConnectionManager 或从 './../service/connectionManager' 导入 ConnectionManager 或从 './../service 导入 {ConnectionManager} /connectionManager'
  • 第二个选项是正确的。如果仍有错误,请提供更多信息。
  • 您在使用 ConnectionManager 的代码中有错误。您使用 ConnectionManager 作为一个函数,但它是一个类。
猜你喜欢
  • 2018-01-27
  • 1970-01-01
  • 2016-03-23
  • 2018-08-07
  • 1970-01-01
  • 2019-11-03
  • 2019-07-28
  • 2018-01-29
  • 1970-01-01
相关资源
最近更新 更多