Webpack提供插件供全球使用Underscore - 错误

时间:2016-06-23 16:29:55

标签: javascript underscore.js webpack

我试图通过Webpack ProvidePlugin全局使用下划线,但是它没有识别下划线,并且在控制台中我收到以下错误。

VM43994:1 Uncaught ReferenceError: _ is not defined(…)

我在index.js中导入下划线(现在我可能不需要供应商捆绑?),我的webpack配置如下所示。在一个阶段,我认为我有它工作(在做供应商捆绑之前),但我现在认为我可能是错的,因为我觉得我已经尝试过我尝试过的所有途径。任何帮助将不胜感激。

const webpack = require('webpack');
const path = require('path');
const precss = require('precss');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const postcssImport = require('postcss-import');

module.exports = {

  context: __dirname + '/frontend',
  devtool: 'source-map',
  entry: {
    app: './index.js',
    vendor: ['underscore'],
  },
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, './static'),
  },
  module: {
    loaders: [
    { test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['es2015'] } },
    { test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css?sourceMap&importLoaders=1!postcss') },
    ],
  },
  plugins: [
    new ExtractTextPlugin('si-styles.css'),
    new webpack.ProvidePlugin({ underscore: 'underscore' }),
    new webpack.optimize.CommonsChunkPlugin(/* chunkName= */'vendor', /* filename= */'vendor.bundle.js', Infinity),
  ],
  postcss: function(webpack) {
    return [
      postcssImport({ addDependencyTo: webpack }), // Must be first item in list
      precss,
      autoprefixer({ browsers: ['last 2 versions'] }),
    ];
  },

};

1 个答案:

答案 0 :(得分:3)

多一点调查和this seems to work

{
    plugins: [
        new webpack.ProvidePlugin({
            _: 'underscore'
        })
    ]
}

同样在您的TS文件中,您可以添加window['_'] = require('underscore')