'Import a JavaScript file with Webpack

I got Webpack up and running and now I'd like to split my code into separate files.

Lets say I have this code in a separate file:

handlebarHelpers.js

handlebars.registerHelper('timeFilter', function(context, block) {
  var f = block.hash.format || "MMM DD, YYYY HH:mm"; //default format
  return moment.unix(context).format(f);
});

Then I would like to include this into my main app.js file via webpack:

webpack.conf.js

const webpack = require('webpack');

module.exports = {
  entry: {
    app: [
      'handlebars',
      'handlebarHelpers.js'
      './js/app.js'
    ],
  },
  output: {
    filename: 'www/theme/js/app.dev.js'
  },
  node: {
    fs: 'empty'
  }
};

This works, but how do I make it execute it in my app.js file? I found a gazillion webpack tutorials but nothing as basic as this.

I tried:

app.js

import handlebars from 'handlebars';
import './handlebarHelpers';

// yadaya create handlebars
$( document ).ready(function() {
    console.log( "ready!" );
});

This does not work:

ReferenceError: handlebars is not defined

But when I have the handlebars helper code inside app.js it works nicely.

What to do?



Solution 1:[1]

In your webpack config you are referencing handlesbarsHelpers and app.js in different directories. but then in your app.js example you are referencing handlesbarsHelpers as if it's in the same directory ass app.js

Try moving them into the same dir. Also you should only need app.js in your entry point if it's importing everything else you need:

webpack.config.js

entry: {
  app: './js/app.js'
},

app.js

import handlebars from 'handlebars';
import './handlebarHelpers';  // make sure this is in same dir as app.js

// yadaya create handlebars
$( document ).ready(function() {
    console.log( "ready!" );
});

Solution 2:[2]

If you use dividab/tsconfig-paths-webpack-plugin, its default extension does not include .js. And you need to do something like this:

resolve: {
  plugins: [new TsconfigPathsPlugin({
    extensions: ['.ts', '.tsx', '.js'],
  })],
  extensions: ['.ts', '.tsx', '.js'],
},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 olore
Solution 2 Kindred