Datatables.net (1.10.22) + Webpack Encore (1.11) + Symfony (5.2.6)

如何解决Datatables.net (1.10.22) + Webpack Encore (1.11) + Symfony (5.2.6)

我正在处理一个 Symfony 5.2.6 项目,我正在尝试在我的项目中使用 datatables.net 库,但找不到正确导入它的方法。

我使用了很多 js/jquery 库,除了数据表之外,一切都运行良好。 (我正在使用 Metronic 管理模板)

packages.json

这是我的 webpack.config.js :

const Encore = require('@symfony/webpack-encore');
const CopyWebpackPlugin = require('copy-webpack-plugin');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')

    .addStyleEntry('basecss','./assets/sass/style.scss')
    .addStyleEntry('pluginscss','./assets/plugins/plugins.scss')
    .addStyleEntry('extrascss','./assets/css/extras.css')

    .addEntry('app','./assets/app.js')
    .addEntry('plugins','./assets/plugins/plugins.js')
    .addEntry('scripts','./assets/scripts.js')

    .addEntry('test','./assets/test.js')

    .addEntry('page-ms-liste','./assets/pages/matiereseche/liste.js')
    
    .addStyleEntry('page-login-css','./assets/pages/authentication/login.css')

    .enableStimulusBridge('./assets/controllers.json')
    
    .splitEntryChunks()
    
    .enableSingleRuntimeChunk()
    
    .cleanupOutputBeforeBuild()
    
    .enableBuildNotifications()
    
    .enableSourceMaps(!Encore.isProduction())
    
    .enableVersioning(Encore.isProduction())

    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    })
    
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

    // enables Sass/SCSS support
    .enableSassLoader()

    .addPlugin(new CopyWebpackPlugin({
        patterns: [
            { from: './assets/images',to: 'images' }
        ],}))

    .addLoader({
        test: require.resolve('jquery'),use: [{
            loader: 'expose-loader',options: {
                exposes: [
                    {
                        globalName: "$",override: true,},{
                        globalName: "jQuery",}
                ]
            }
        }]})

    .addLoader({
        test: '/datatables\.net.*/',use: [{
            loader: 'imports-loader',options: {
                imports: {
                    moduleName: 'jquery',name: '$',additionalCode: "var define = false;"
            }
        }]})


;
const config = Encore.getWebpackConfig();

module.exports = config;

我也尝试使用 .autoProvidejQuery()

在我的scripts.js里面我有:

window.jQuery = window.$ = require('jquery');
// ...    
require('datatables.net');
require('datatables.net-bs4');

然后在我的 js 文件中:

var t = $("#datatable");
        t.DataTable(.....)

错误:

未捕获的类型错误:$(...).DataTable 不是函数

我发现了很多关于这个主题的主题,但是我尝试了所有方法都没有成功(使用加载器,...) 我也尝试从 CDN 和数据表导入 jquery,但我有一个 jquery 问题(jquery 未定义)

如果有人有想法...

谢谢。

解决方法

删除

window.jQuery = window.$ = require('jquery');

然后,你可以这样导入数据表:

import $ from "jquery";
require('datatables.net-bs4')( window,$ );

这样,DataTable 应该会被识别出来,你就可以使用它了。

,

经过相当长的时间测试 Stackoverflow 的各种答案后,我设法使它起作用(在 Guillaume F. 和 Dylan Kas 的帮助下)。

这些是文件:

webpack.config.js

const Encore = require('@symfony/webpack-encore');
const CopyWebpackPlugin = require('copy-webpack-plugin');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')

     // Main Js file
    .addEntry('app','./assets/app.js')
     
    // In my case Datatable init code is in this file. Don't forget to load this asset from your template page with the shortcut : {{ encore_entry_script_tags('my-page') }}
    .addEntry('my-page','./assets/pages/my-page.js')

    //.. Other imports here ..
    /*.addEntry('scripts','./assets/scripts.js')*/

    .splitEntryChunks()

    .enableSingleRuntimeChunk()

    .cleanupOutputBeforeBuild()

    .enableBuildNotifications()

    .enableSourceMaps(!Encore.isProduction())

    .enableVersioning(Encore.isProduction())

    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    })

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })
    
    .addPlugin(new CopyWebpackPlugin({
        patterns: [
            { from: './assets/images',to: 'images' }
        ],}))

;
const config = Encore.getWebpackConfig();

// Without this,I have issues with my DT.net requires
config.module.rules.unshift({
    parser: {
        amd: false,}
});

module.exports = config;

我的app.js文件

window.jQuery = window.$ = require('jquery');

require('bootstrap');

window.Popper = require('popper.js').default;

// Needed form Datatables Buttons plugin
window.JSZip = require('jszip');
const pdfMake = require('pdfmake/build/pdfmake.js');
const pdfFonts = require('pdfmake/build/vfs_fonts.js');
pdfMake.vfs = pdfFonts.pdfMake.vfs;


require('datatables.net')(window,$);
require('datatables.net-bs4')(window,$);
require('datatables.net-buttons/js/dataTables.buttons.min.js')(window,$);
require('datatables.net-buttons-bs4')(window,$);
require('datatables.net-buttons/js/buttons.flash.js')(window,$);
require('datatables.net-buttons/js/buttons.html5.js')(window,$);
require('datatables.net-buttons/js/buttons.print.js')(window,$);

我的packages.json

{
    "dependencies": {
        // others imports above
        "bootstrap": "^4.6.0","datatables.net": "^1.10.24","datatables.net-autofill-bs4": "^2.3.5","datatables.net-bs4": "1.10.24","datatables.net-buttons-bs4": "^1.7.0","datatables.net-colreorder-bs4": "^1.5.2","datatables.net-fixedcolumns-bs4": "^3.3.2","datatables.net-fixedheader-bs4": "^3.1.7","datatables.net-keytable-bs4": "^2.5.3","datatables.net-responsive-bs4": "^2.2.6","datatables.net-rowgroup-bs4": "^1.1.2","datatables.net-rowreorder-bs4": "^1.2.7","datatables.net-scroller-bs4": "^2.0.3","datatables.net-select-bs4": "^1.3.1","jquery": "^3.6.0","jszip": "^3.5.0","pdfmake": "^0.1.36","popper.js": "^1.16.1",},"devDependencies": {
        "@symfony/stimulus-bridge": "^2.0.0","@symfony/webpack-encore": "^1.0.0","copy-webpack-plugin": "^8.1.0","core-js": "^3.0.0","expose-loader": "^2.0.0","imports-loader": "^2.0.0","lodash": "^4.17.13","regenerator-runtime": "^0.13.2","sass": "^1.32.8","sass-loader": "11.0.0","script-loader": "^0.7.2","stimulus": "^2.0.0","webpack-notifier": "^1.6.0"
    },"license": "UNLICENSED","private": true,"scripts": {
        "dev-server": "encore dev-server","dev": "encore dev","watch": "encore dev --watch","build": "encore production --progress"
    }
}

最后我的文件初始化了数据表(我每页使用一个条目 js 文件): page.js

"use strict";

var MyPage = {
    init: function () {
        const table = $('#datatable').DataTable({
            buttons: [
                {
                    extend: 'print',exportOptions: {
                        columns: [0,1,2,3]
                    }
                },{
                    extend: 'excelHtml5',],columnDefs: [
                {
                    width: '75px',targets: 4,});

        $('#export_print').on('click',function(e) {
            e.preventDefault();
            table.button(0).trigger();
        });

        $('#export_excel').on('click',function(e) {
            e.preventDefault();
            table.button(1).trigger();
        });
    },};
jQuery(document).ready(function () {
    MyPage.init();
});

请注意,在我的情况下,我从 2 个 html 元素切换按钮。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res