Javascript es6 + Webpack引用导入

时间:2018-01-31 21:33:39

标签: javascript webpack electron babel es6-class

我想弄清楚为什么我可以从一个文件引用导入,但不能引用另一个文件 (我认为这与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

所以我可以通过app里面的app调用类,但是反过来不能这样做吗?为什么呢?

感谢提前回复

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

感谢评论者Luke和Li357。 我打破了我的大脑,并将自己与文件夹名称和文件名混淆。

问题是我从相同位置导入文件并导致循环依赖性错误。

解决。