webpack配置jquery以及jquery插件

项目目录大概结构:

project
  |- app
  |   |- vendor
  |   |    |- plugins
  |   |    |    |- plugin-1.js
  |   |    |    |- plugin-2.js
  |   |    |    |- ...
  |   |    |
  |   |    |- jquery.js
  |   |
  |   |- jquery-with-plugins.js
  |   |- main.js
  |
  |- js
  |   |- bundle.js
  |
  |- webpack.config.js
  |- package.json
 ...
 

关键文件内容:

// app/jquery-with-plugins.js
require('vendor/jquery');
req = require.context('vendor/plugins', true, /\.js$/);
req.keys().forEach(function (plugin) {
  req(plugin);
});

module.exports = jQuery;

// app/main.js
var $ = require('jquery');

$(function () {
  $('.selector-1').use_plugin_1();
  $('.selector-2').use_plugin_2();
});

// webpack.config.js
var path = require('path');

module.exports = {
  context: path.join(__dirname, 'app'),
  entry: './main',
  output: {
    path: path.join(__dirname, 'js'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        include: [
          path.join(__dirname, 'app/vendor')
        ],
        loader: 'script'
      }
    ]
  },
  resolve: {
    alias: {
      'jquery$': path.join(__dirname, 'app/jquery_with_plugins'),
      'vendor': path.join(__dirname, 'app/vendor')
    }
  },
  extensions: ['', '.js']
};

// package.json
{
  "name": "temp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "build": "webpack --progress --colors"
  },
  "devDependencies": {
    "node-libs-browser": "^0.5.0",
    "script-loader": "^0.6.1",
    "webpack": "^1.9.4"
  }
}

关于其他webpack优化可以看看这里

    原文作者:alwaysVe
    原文地址: https://segmentfault.com/a/1190000005184341
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞