kartsims
kartsims

Reputation: 1008

Webpack compiling ES6 into module

I am trying to compile ES6 to a file using Webpack and can't figure out why the code is not usable as it is.

Side note : This is meant to be a plugin for VueJS

I start with a simple file that exports a single function such as

exports.install = () => {
  ...
}

Webpack uses babel-loader and babel-preset-es2015 to compile it.

You may find webpack config, source and compiled files in this gist.

My problem is the result is not "requirable" in my Vue app... It has some weird stuff around the core needed exports.install statement. When I remove all this stuff and leave just exports.install = ... it is OK, otherwise I just don't get anything out of it.

I am using it in another app built with webpack, through an import statement.

Upvotes: 0

Views: 648

Answers (1)

also
also

Reputation: 974

Without an output.libraryTarget option, webpack will generate a bundle you can include via a <script> tag, but not import. I think this is what you're seeing.

If you want to import (or require) the result of your webpack build, you should set libraryTarget to commonjs2

  output: {
    filename: 'index.js',
    libraryTarget: "commonjs2"
  },

With this libraryTarget configuration, the webpack output will look like module.exports = /* ... the "weird stuff" */, so when you import it, you'll get the exported function you expect.


If all you're doing is compiling a single file or set of files that will be imported in another webpack build, you might consider not using webpack at all, and instead using the Babel CLI directly. In your Gist, you're not getting anything from webpack other than wrapping your module in some extra webpack bootstrap code.

Upvotes: 3

Related Questions