1

I don't understand why this is being so complicated I want my project to have 2 separate work spaces where one is a library that will be distributed and the other will be used for testing... this is how i have the file structure

project  
--engine
---math
----vec2.js
---dist  
----library.js  
---main.js  
--sandbox  
---main.js 

I want to build the "engine" project with webpack and es6 modules so I get a "library" file that can be used in "sandbox".

The "engine" main file would look something like this

import vec2 from './math/vec2';
export default class Library {
   constructor() {
      this.vec2 = vec2;
   }
}

An then the sandbox main file would look something like this

import lib from '../engine/dist/library';
const game = new lib();

The problem is when I build the "library.js" file with webpack and import it in the "sandbox" main file I can't call any of the classes therein. I get this error.

Uncaught TypeError: o.default is not a constructor
    at Object.<anonymous> (library.js:1)
    at e (library.js:1)
    at library.js:1
    at library.js:1  

My webpack.config.js file looks like this

    var webpack = require('webpack');
module.exports = {
    context: __dirname,
    entry: __dirname+"/main.js",
    output: {
        path: __dirname+"/dist",
        filename: "library.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules)/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin()
    ]
};  

I must be missing some configuration webpack needs or some plugin that will make this work. I simply want to build the library with webpack using es6 modules so it can be used in another project but I have no idea how to configure it. I'm using babel for transpilling es6 to es5

1 Answer 1

1

You need to configure output.libraryTarget. In this case the target commonjs-module is appropriate. So your output would be:

output: {
    path: __dirname+"/dist",
    filename: "library.js",
    libraryTarget: "commonjs-module"
},

The different targets are described in the docs. And you might also want to read Guides - Authoring Libraries.

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

1 Comment

Man thank you so much... I been clueless about how this was gonna work, and thank you for the link.

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.