1

I am learning to use webpack for first time. I am really stuck with something that was never a problem with gulp, that is the way it scopes different files.

I have a file that contains multiple standalone functions (helpers.js).

function a() {
}
function b() {
}
function c() {
}

Based on my reading here do I need to import each function separately? How do I import the whole file?

From the example in link:

a.js:

export var a = 4;

b.js

import { a } from "./b.js";
var b = a+1;
console.debug(b);
TheRealPapa
  • 4,393
  • 8
  • 71
  • 155
  • Try with `import { a } from "./b";` (not end with `.js`) –  Aug 09 '17 at 02:16
  • Sorry Alan, the question is how to import the external file with functions and make each function available to the global scope. Same as global variables – TheRealPapa Aug 09 '17 at 02:18
  • lol. Sorry, I haven't read your question:). You can refer this question: [ES6+ javascript module export options](https://stackoverflow.com/questions/25494365/es6-javascript-module-export-options) I think it's good to start. –  Aug 09 '17 at 02:27

1 Answers1

3

I suspect that you have used some concatenation plugin for gulp and your scope was "shared". With ES6 modules, you have to define exactly what functions to export and import because the scope of each file is separate.

So in your example, we can do it this way:

  1. Create default export in helpers.js and define what data to export.

helpers.js

function a(){}
function b(){}
function c(){}

export default {a,b,c}

And import data this way:

import myHelpers from 'helpers'

Then to use helper a, you will need to call myHelpers.a()

  1. Another approach is to create "named" exports

helpers.js:

export function a(){}
export function b(){}
export function c(){}

To import all data use:

import * as myHelpers from 'helpers'

Then similar to the previous example, call -> myHelpers.a()

But typing "myHelpers" is not always convenient, so here we can use named exports additional benefit - you can import it by a name, so we can do it like this:

import {a,b,c} from 'helpers'

Then you can call a()

You have to type all the names you want to import. There is no "shortcut" for that.

Why this way?

  • better control on what exactly you import to your code, optional "tree shaking"
  • no conflicts between imported modules

Webpack - ProvidePlugin

Ok, but what if you use those helpers really often? Do you need to import them everywhere? Technically - yes. But Webpack can automate that for us, have a look on Webpack - ProvidePlugin which automatically loads modules instead of having to import them everywhere.

For Webpack 3, if you go with the first solution it will look like this:

new webpack.ProvidePlugin({
  helpers:['path/to/module/helpers', 'default'],
}), 

That will make helpers available like a "global", and you will be able to use helpers.a()

Marian Gibala
  • 874
  • 7
  • 9