【问题标题】:Using javascript from typescript, bundling using webpack. Runtime errors使用来自 typescript 的 javascript,使用 webpack 捆绑。运行时错误
【发布时间】:2016-12-18 02:58:48
【问题描述】:

我有一个非常简单的 javascript 函数:

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;
}

这是在 alphanum.js 中。

我想在打字稿文件中使用它。所以我做了以下事情:

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

我正在使用 webpack 将所有内容捆绑在一起。这似乎很好,没有错误,没有问题。

当我尝试使用该功能时,客户端出现错误:

EXCEPTION: ReferenceError: alphanum is not defined

我觉得我错过了一些非常明显的东西。我在 webpack 和需求方面做错了吗?

编辑:

这是我的 webpack 配置:

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"
  ]
}

这是一个 Angular2 应用程序,如果有帮助,webpack 配置主要来自:https://angular.io/docs/ts/latest/guide/webpack.html

【问题讨论】:

    标签: javascript typescript webpack


    【解决方案1】:

    ReferenceError: 字母数字未定义

    默认情况下,webpack 每个文件都被认为是一个模块。您将其用作global

    修复

    如果你仍然希望它是全球性的,你会:

    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;
    

    【讨论】:

    • 但是为什么他在浏览器中出现导出关键字的错误?
    • 是的,这似乎更好!您知道将其保留为模块的语法吗?
    【解决方案2】:

    你没有从 alphanum.js 导出你的函数,这就是它未定义的原因。

    export function alphanum(a, b) { 
    

    来自您的 alphanum.js,它应该可以工作。

    【讨论】:

    • 不喜欢 "SyntaxError: Unexpected token export"
    • 这不是说它没有编译。浏览器不理解导出所以你需要设置 webpack 来解析 js 文件 resolve: { extensions: ["", ".ts", ".js"] } please read this also this
    • 我有。 Webpack 将函数(与导出)放在包中。感谢您的尝试。
    • 你的目标是 es6。 es6 浏览器尚不支持导出
    • 请分享你的 webpack 配置和 tsconfig。您是否在浏览器中收到此错误?
    猜你喜欢
    • 2016-07-05
    • 1970-01-01
    • 2018-08-23
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2018-04-09
    • 1970-01-01
    相关资源
    最近更新 更多