Использование Bootstrap с Truffle

У меня проблемы с запуском начальной загрузки с моим трюфельным приложением. Журналы показывают, что сборка проходит нормально, но когда я truffle serveоткрываю ее в браузере, она жалуется, что «JavaScript Bootstrap требует jQuery». Лог для справки:

Hash: d9e8c287d453464242a2
Version: webpack 2.6.1
Time: 10597ms
                                 Asset     Size  Chunks                    Chunk Names
  f4769f9bdb7466be65088239c12046d1.eot  20.1 kB          [emitted]         
  89889688147bd7575d6327160d64e760.svg   109 kB          [emitted]         
  e18bbf611f2a2e43afc071aa2f4e1512.ttf  45.4 kB          [emitted]         
 fa2772327f55d8198301fdb8bcfc8158.woff  23.4 kB          [emitted]         
448c34a56d699c29117adc64c43affeb.woff2    18 kB          [emitted]         
                                app.js  1.38 MB       0  [emitted]  [big]  main
                            index.html  4.03 kB          [emitted]         
                             jquery.js  86.7 kB          [emitted]         
  [67] ./~/web3/index.js 193 bytes {0} [built]
  [68] ./~/babel-runtime/core-js/symbol.js 87 bytes {0} [built]
  [69] ./~/babel-runtime/core-js/symbol/iterator.js 96 bytes {0} [built]
  [70] ./~/babel-runtime/helpers/typeof.js 1.07 kB {0} [built]
  [88] ./~/style-loader/addStyles.js 6.91 kB {0} [built]
  [97] ./app/vendor/bootstrap-3.3.7-dist/js/bootstrap.min.js 45.3 kB {0} [built]
  [98] ./app/vendor/jquery-3.2.1.min.js 125 kB {0} [built]
  [99] ./build/contracts/Lottery.json 7.45 kB {0} [built]
 [100] ./app/stylesheets/style.css 911 bytes {0} [built]
 [101] ./app/vendor/bootstrap-3.3.7-dist/css/bootstrap.min.css 959 bytes {0} [built]
 [102] ./~/truffle-contract/index.js 2.64 kB {0} [built]
 [103] ./app/javascripts/app.js 3.12 kB {0} [built]
 [104] ./~/babel-runtime/core-js/object/define-property.js 103 bytes {0} [built]
 [105] ./~/babel-runtime/core-js/object/get-prototype-of.js 104 bytes {0} [built]
 [248] (webpack)/buildin/amd-options.js 82 bytes {0} [built]
    + 235 hidden modules

В журнале видно, что начальная загрузка создается до jQuery, хотя я импортирую их в правильном порядке в свой app.js:

// Import libraries we need.
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract';

// Import our contract artifacts and turn them into usable abstractions.
import lottery_artifacts from '../../build/contracts/Lottery.json';

import "../vendor/jquery-3.2.1.min.js";
import "../vendor/bootstrap-3.3.7-dist/js/bootstrap.min.js";
import "../vendor/bootstrap-3.3.7-dist/css/bootstrap.min.css";
import "../stylesheets/style.css";

// Lottery is our usable abstraction, which we'll use through the code below.
var Lottery = contract(lottery_artifacts);

// The following code is simple to show off interacting with your contracts.
// As your needs grow you will likely need to change its form and structure.
// For application bootstrapping, check out window.addEventListener below.
var accounts;
var account;

window.App = {
  start: function() {
    var self = this;

    // Bootstrap the Lottery abstraction for Use.
    Lottery.setProvider(web3.currentProvider);

    // Get the initial account balance so it can be displayed.
    web3.eth.getAccounts(function(err, accs) {
      if (err != null) {
        alert("There was an error fetching your accounts.");
        return;
      }

      if (accs.length == 0) {
        alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
        return;
      }

      accounts = accs;
      account = accounts[0];

      self.refreshBalance();
    });
  }
};

window.addEventListener('load', function() {
  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 Lottery, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask")
    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);
  } else {
    console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }

  App.start();
});

Может ли это быть проблемой? Вот мой webpack.config.js для справки:

const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: './app/javascripts/app.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'app.js'
  },
  plugins: [
    // Copy our app's index.html to the build folder.
    new CopyWebpackPlugin([
      { from: './app/index.html', to: "index.html" },
    ])
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015'],
          plugins: ['transform-runtime']
        }
      },
      {
       test: /\.css$/,
       use: [ 'style-loader', 'css-loader' ]
      },
      { test: /\.json$/, use: 'json-loader' },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: [ 'url-loader?limit=10000&mimetype=application/font-woff' ]
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: [ 'file-loader' ]
      }
    ]
  }
}
Этот вопрос не относится к эфириуму. stackoverflow.com/questions/37651015/…

Ответы (1)

Вам нужно использовать ProvidePlugin из webpack , потому что загрузчик ожидает файл global.jQuery. Добавьте следующее в конфигурацию сборки:

// webpack.config.js
module.exports = {
    ...
    plugins: [
        new webpack.ProvidePlugin({
           $: "jquery",
           jQuery: "jquery"
       })
    ]
};

Это устанавливает global.$и global.jQueryв jqueryпакет npm. Теперь вы можете удалить свой jqueryоператор импорта, если вам больше нигде не нужен jquery.