Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to export function with webpack

I intend to bundle all my .js using webpack. I tried with a very simple example as following.

Function to bundle in a test.js file :

function test() {
  console.log('hello');
}

Webpack configuration :

module.exports = [{
  {
    output: {
      filename: 'test.js',
      path: __dirname + '/public/javascript/dist'
    },
    entry: [
      './public/javascript/test.js'
    ]
  }
]

Code to test :

<html>
<head></head>
<body>

    <script src="./javascript/dist/test.js"></script>

<script type="text/javascript">

window.onload = function()
{
    test();
}

</body>
</html>

But I receive the following error : Uncaught ReferenceError: test is not defined.

Question : why?

[Edit] Reponse is : "export" is missing. Thanks to that, I updated as following:

Code to export :

export function Test() {
  this.t = 1;

  Test.prototype.toto = function()
  {
    console.log('hello')
  }
}

Webpack conf :

{
output: {
  filename: 'test.js',
  path: __dirname + '/public/javascript/dist',
  library: 'test',
  libraryTarget: 'window'
},
entry: [
  './public/javascript/poc/test.js'
]
}

To create the object, I have to do : var t = new test.Test(); It's a bit heavy... Is there a way to only have to make : var t = new Test(); ?

like image 421
MrFlo Avatar asked Aug 22 '17 12:08

MrFlo


People also ask

Does webpack use CommonJS?

Webpack supports the following module types natively: ECMAScript modules. CommonJS modules.

What is chunkFilename webpack?

So the filename is used for generating independent entry bundles, while chunkFilename is used for bundles that are auto-generated by Webpack during code splitting.

What is libraryTarget in webpack?

This is according to their documentation: "libraryTarget: "umd" - This exposes your library under all the module definitions, allowing it to work with CommonJS, AMD and as global variable." Also, I built the exact same code with Webpack 3 and it produced a proper bundle.


1 Answers

why?

Because you haven't exported anything from your entry point and, by default, webpack generates output in umd format without polluting global scope.

You first have to export your function:

export default function test() {
  console.log('hello');
}

Then specify "library" and "libraryTarget" in your webpack config. Docs. For example:

output: {
  filename: 'test.js',
  path: __dirname + '/public/javascript/dist',
  library: 'test',
  libraryTarget: 'window',
  libraryExport: 'default'
},

this will generate code that adds window.test = _entry_return_.default .

like image 188
Yury Tarabanko Avatar answered Sep 20 '22 14:09

Yury Tarabanko