Rails 6 + yarn + 数据表问题

Rails 6 + yarn + datatables issue

我遇到了 webpacker 的问题。我正在使用 Rails 6.beta3 并尝试将数据表添加到我的应用程序。我的步骤:

 yarn add datatables.net-dt

然后在 app/javascript/packs/application.js:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
import 'popper.js/dist/popper.js';

require( 'datatables.net-dt' )();

config/webpack/environment.js:

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
module.exports = environment
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
}))

在此之后,如果加载页面,我在 js 控制台中收到错误消息:

Uncaught TypeError: Cannot set property '$' of undefined
    at DataTable (jquery.dataTables.js:129)

jquery.dataTables.js:

 var DataTable = function DataTable(options) {
    this.$ = function (sSelector, oOpts) { // <---------error is here. Turns out this is not defined variable
      return this.api(true).$(sSelector, oOpts); 
    };

有什么想法吗?提前致谢

哎呀。是我的错。我发现了问题。在 app/javascript/packs/application.js 结束时出现错误。我认为它不会对整体性能产生影响,但在消除这个问题后开始正常工作。

我的app/javascript/packs/application.js


require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
import 'popper.js/dist/popper.js';

我的application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
import 'popper.js/dist/popper.js';
require( 'datatables.net-dt' )();

结果是

jquery.dataTables.js:129 Uncaught TypeError: Cannot set property '$' of undefined
    at DataTable (jquery.dataTables.js:129)
    at Module../app/javascript/packs/application.js (application.js:38)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83

奇怪的是堆栈的 bootstrap 部分!

我的app.js

// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
require('select2');
import 'popper.js/dist/popper.js';
require("chart.js");
require("leaflet");


import $ from 'jquery';
window.jQuery = $;
window.$ = $;
// var dt = require( 'datatables.net-dt' );

// var dt = require( 'datatables.net-bs4' )( window, window.$ );

require('datatables.net-bs4');
var moment = require('moment');
window.moment = moment
require('bootstrap-daterangepicker');

var feather = require('feather-icons/dist/feather.js')


function onready() {
  feather.replace()
  console.log('onready')
}

$(document).on('ready turbolinks:load', onready);

/* globals Chart:false, feather:false */



(function () {  
  feather.replace()

}())