0

I have a dead simple javascript function:

function alphanum(a, b) {
  function chunkify(t) {
    var tz = [], x = 0, y = -1, n = 0, i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        tz[++y] = "";
        n = m;
      }
      tz[y] += j;
    }
    return tz;
  }

  var aa = chunkify(a);
  var bb = chunkify(b);

  for (x = 0; aa[x] && bb[x]; x++) {
    if (aa[x] !== bb[x]) {
      var c = Number(aa[x]), d = Number(bb[x]);
      if (c == aa[x] && d == bb[x]) {
        return c - d;
      } else return (aa[x] > bb[x]) ? 1 : -1;
    }
  }
  return aa.length - bb.length;
}

This is in alphanum.js.

I want to use it in a typescript file. So I have done the following:

declare function alphanum(param1: any, param2: any): number;
require("./../utils/alphanum.js");

I am using webpack to bundle everything together. This seems fine, no errors, no problems.

When I try to use the function I get errors on the client:

EXCEPTION: ReferenceError: alphanum is not defined

I feel like I am missing something really obvious. Am I doing anything wrong with webpack and requires?

Edit:

Here's my webpack config:

webpack.common.js:

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['', '.js', '.ts'],
    root: [
      helpers.root('./src'),
      helpers.root('node_modules')
    ],
     alias: {
      // bind version of jquery-ui
      "jquery.ui.core": "jqueryui/jquery-ui.min.js",     
      "jquery.ui.widget": "jqueryui/jquery-ui.min.js"
     }
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['ts', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw'
      }
    ]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    }),

    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
      "window.jQuery":"jquery"})
  ]
};

webpack.dev.js:

var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

module.exports = webpackMerge(commonConfig, {
  devtool: 'source-map',
  debug: true,

  output: {
    path: helpers.root('dist'),
    publicPath: 'http://localhost:8080/',
    filename: '[name].js',
    chunkFilename: '[id].chunk.js'
  },

  plugins: [
    new ExtractTextPlugin('[name].css')
  ],

  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors":true,
    "outDir": "dist"
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

It's an Angular2 app, if that helps, webpack config came mostly from: https://angular.io/docs/ts/latest/guide/webpack.html

2 Answers 2

2

ReferenceError: alphanum is not defined

By default with webpack each file is consider a module. You are using it as a global.

Fix

If you still want it global you would:

function alphanum(a, b) {
  function chunkify(t) {
    var tz = [], x = 0, y = -1, n = 0, i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        tz[++y] = "";
        n = m;
      }
      tz[y] += j;
    }
    return tz;
  }

  var aa = chunkify(a);
  var bb = chunkify(b);

  for (x = 0; aa[x] && bb[x]; x++) {
    if (aa[x] !== bb[x]) {
      var c = Number(aa[x]), d = Number(bb[x]);
      if (c == aa[x] && d == bb[x]) {
        return c - d;
      } else return (aa[x] > bb[x]) ? 1 : -1;
    }
  }
  return aa.length - bb.length;
}

// THIS IS WHERE THE MAGIC HAPPENS
global.alphanum = alphanum;
Sign up to request clarification or add additional context in comments.

2 Comments

But why he's getting error in the browser for export key word?
Yes, this seems better! And do you know the syntax to keep it as a module?
1

You are missing to export your function from alphanum.js that's why it is undefined.

export function alphanum(a, b) { 

from your alphanum.js and it should work.

7 Comments

It doesn't like it "SyntaxError: Unexpected token export"
tha't prebebly it's not compiling. browser don't understand export so you need to set webpack to resolve js files resolve: { extensions: ["", ".ts", ".js"] } please read this also this
I have that. Webpack is putting the function (with the export) in the bundle. Thanks for trying.
Are you targeting es6. Export is not supported yet in browser with es6
Please share your webpack config and tsconfig. Are you getting this error in browser?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.