开发者问题收集

Rails 6 + yarn + 数据表问题

2019-04-25
2415

我在使用 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); 
    };

有什么想法吗?提前致谢

3个回答

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

snake
2019-04-25

我的 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()

}())
snake
2019-11-18

我的 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';

snake
2019-11-18