【问题标题】:Javascript es6 + Webpack referencing importsJavascript es6 + Webpack 引用导入
【发布时间】:2018-07-11 03:10:13
【问题描述】:

我正在尝试找出为什么我可以从一个文件中引用导入,但不能从另一个文件中引用 (我认为这与 javascript 的工作方式有关,并且在定义变量之前我无法引用它......如果是这种情况,那么我希望你们中的一个可以给我一些解决方法的参考。 ) 我正在使用 webpack 和 babel 构建一个电子应用程序。

我的 webpack.config.js 看起来像这样:

var path = require('path');
var webpack = require('webpack');

module.exports = {
 entry: {
  app: ['./app/src/app.js', './app/src/test.js']
 },
 output: {
  path: __dirname,
  filename: './app/lib/bundle.js'
 },

 module: {
  loaders: [
   {
    test: /.js?$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
     presets: ['env']
    }
   }
  ]
 },
};

还有我的 app.js

import { test, foo } from './app';

class app {
 constructor() {
  console.log("hello from app.js");
 }
}

// let a = new test(); // gives error (shown below)
// foo(); // same exact error but referencing function instead of constructor

export { app };

还有 test.js

import { app } from './app';

class test {
 constructor() {
  console.log("hello from test.js");
 }
}

let foo = () => console.log("foo");

let b = new test(); // works as expected

export { test, foo };

错误如下:

Uncaught TypeError: _app.test is not a constructor
    at Object.<anonymous> (bundle.js:88)
    at __webpack_require__ (bundle.js:20)
    at Object.defineProperty.value (bundle.js:97)
    at __webpack_require__ (bundle.js:20)
    at Object.defineProperty.value (bundle.js:63)
    at bundle.js:66

所以我可以在测试中从应用程序调用类,但不能反过来做同样的事情?为什么?

感谢您提前回复

【问题讨论】:

  • 等等什么?你为什么要从自己导入一些东西?您为什么要尝试从应用 inside app 导入 test 和 foo??

标签: javascript webpack electron babeljs es6-class


【解决方案1】:

这是一个循环依赖问题。您的 app 导入 test,而后者又导入 app

【讨论】:

  • 我认为他们在import { test, foo } from './app' 中打错了字,意思是从'./test' 导入。如果是这样,那么他们可能会从我假设的循环依赖中得到堆栈溢出。
【解决方案2】:

感谢评论者 Luke 和 Li357。 我为此伤透了脑筋,把自己与文件夹名和文件名混淆了。

问题是我从同一个地方导入文件并导致循环依赖错误。

解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2018-07-04
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    相关资源
    最近更新 更多