在另一个构造函数中使用导入的类

时间:2017-04-14 10:30:14

标签: javascript ecmascript-6 babeljs

ES6语法入门,为什么Main中的MesageTester.Create("bar");失败?

我在 src / app.js (也是webpack条目)中有以下内容:

import {MessageTester} from './helpers/MessageTester';

class Main {
    constructor() {
        //does run
        console.log("trying..");

        //causes crash "Uncaught ReferenceError: MesageTester is not defined"
        MesageTester.Create("bar");
    }
}

//is fine
MessageTester.Create("foo");

//for testing
new Main();

在另一个文件 src / helpers / MessageTester.js 中,我有这个:

class MessageTester {
    constructor(msg) {
        document.querySelector('#root').innerHTML = `<p>` + msg + `</p>`;
    }

    static Create(msg) {
        return new MessageTester(msg);
    }
}

export {MessageTester};

如评论中所述,MessageTester.Create()在Main之外工作,Main的构造函数正在运行。

如果它是相关的,这是我的webpack配置(作为旁边 - 我不确定源地图是否正常工作......可能与此处的错误相关但不确定):

// webpack.config.js
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const config = {
    context: path.resolve(__dirname, 'src'),
    entry: {
        jistudio: './app.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js',
        sourceMapFilename: '[name].map',
        chunkFilename: '[id].chunk.js'
    },
    module: {
        rules: [{
            test: /\.js$/,
            include: path.resolve(__dirname, 'src'),
            use: [{
                loader: 'babel-loader',
                options: {
                    presets: [
                        ['es2015', {modules: false}]
                    ]
                }
            }]
        }]
    },
    devtool: 'eval-source-map',
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html',
            chunksSortMode: 'dependency'
        }),
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, 'assets'),
            }
        ]),
        new webpack.optimize.UglifyJsPlugin({sourceMap: true})
    ],
    devServer: {
        contentBase: path.join(__dirname, "dist"),
        compress: true,
        port: 3000
    }
}

module.exports = config

1 个答案:

答案 0 :(得分:0)

缺少s

MessageTester.Create("bar");