【发布时间】:2016-06-23 14:29:17
【问题描述】:
我正在尝试从我的 html 中删除 javascript 库的脚本标签,因此已从模板页面中删除了 underscore.js。
要替换它,在我的 index.js(webpack 入口点)中,我有以下内容
import 'underscore';
当我这样做时,webpack 输出的 bundle.js 文件的大小增加了 50k,所以我知道该库在 bundle.js 中。但是,当我尝试在包含 bundle.js 的页面上的控制台中使用下划线时,下划线不可用。
任何想法都将不胜感激。
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: './index.js',
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') },
],
},
vendor: [
'underscore',
],
plugins: [
new ExtractTextPlugin('si-styles.css'),
new webpack.ProvidePlugin({
underscore: 'underscore',
}),
],
postcss: function(webpack) {
return [
postcssImport({ addDependencyTo: webpack }), // Must be first item in list
precss,
autoprefixer({ browsers: ['last 2 versions'] }),
];
},
};
【问题讨论】:
-
你不能调用
_,即使你已经在你的一个模块中导入了它,因为像ES6import语句这样的模块系统旨在避免污染全局空间。需要将该模块分配给全局范围或全局对象 (window),以便您获得对它的引用并在您导入它的模块之一之外使用它。见the WebPack docs for how to get WebPack to do this for you for any module。
标签: javascript underscore.js webpack