0

I'm just getting started working with webpack, but I'm stumped at a rather simple problem.

To try to solve it, I've been looking around the web, but for some reason I can't find examples using vanilla javascript function methods with webpack. I have no problem exporting, importing, and executing imported functions.

The problem is I can't execute imported function methods, and I don't understand why. The functions are imported correctly, and can be executed. The methods cannot be executed.

In this case, I can execute model(), but when I try to call model.alertone(), I get the error "model.alertone is not a function".

Here is the code:

model.js:

function model() {

    var alertone = () => {alert("This works")};


    return {
        alertone
    }

 };

export default model;

index.js:

import model from "./model.js";


model();
model.alertone();

Webpack configuration:

const path = require('path');

module.exports = {
  mode: "development",
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  }
};

0

1 Answer 1

2

This is not a problem with webpack; this is a problem with your program. Why?

Well, first of all, you wrote your model function to return an object, like so:

function model() {
  // Define the 
  var alertone = () => {alert("This works")};

  // Return an object
  return {
    alertone
  }
};

Then, you imported the model function, and called it:

model();
model.alertone();

But there's a problem with that. The model function returns an object, but it doesn't add any properties to the model function itself. Because of that, the model function will have no properties (except for the native ones), and so you can't call alertone.

You probably meant to do this:

var result = model();
result.alertone();

That's all you need to do.

Sign up to request clarification or add additional context in comments.

1 Comment

This solved it. Thank you for saving me from madness. What a dumb mistake. Thank you so much! If you have any recommendations on terms / concepts I should read up on, I would appreciate it. From your answer and a quick search, maybe that would be Prototyping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.