简体   繁体   English

如何使用 Webpack 将 jQuery UI 包含到我的项目中?

[英]How to include jQuery UI into my project using Webpack?

I started a new project using React Slingshot and am trying to use jQuery UI accordions .我使用React Slingshot开始了一个新项目,并尝试使用jQuery UI 手风琴 I have installed the jQuery UI plugin with NPM using npm install --save jquery-ui .我已经使用npm install --save jquery-ui安装了带有 NPM 的 jQuery UI 插件。 As far as I understand, Webpack automatically bundles my Javascript into a bundles.js based on my Webpack config, and is included on my index.ejs page.据我了解,Webpack bundles.js根据我的 Webpack 配置自动将我的 Javascript 捆绑到一个bundles.js ,并包含在我的index.ejs页面中。 However, I'm getting this error, which tells me that the jQuery UI plugin is not being loaded to the page:但是,我收到此错误,它告诉我 jQuery UI 插件未加载到页面:

Uncaught TypeError: $(...).accordion is not a function

How can I include this plugin?我怎样才能包含这个插件? Below I have included my code - let me know if there are any other files you'd like to see.下面我包含了我的代码 - 如果您想查看任何其他文件,请告诉我。

index.ejs:索引.ejs:

<!DOCTYPE html>
<html lang="en">
<!--
  **NOTE:** This is a template for index.html. It uses ejs and htmlWebpackPlugin to generate a different index.html for each environment. htmlWebpackPlugin will dynamically add references to the scripts and styles that it bundles to this file. The generated bundles have hash-based filenames, so it's necessary to add the references dynamically.
  For more info on ejs, see http://www.embeddedjs.com/. For examples of using it with htmlWebpackPlugin, see https://github.com/jaketrent/html-webpack-template/blob/master/index.ejs
  -->
<head>
  <% if (htmlWebpackPlugin.options.trackJSToken) { %>
  <script>window._trackJs = {token: '<%= htmlWebpackPlugin.options.trackJSToken %>'};</script>
  <script src="https://d2zah9y47r7bi2.cloudfront.net/releases/current/tracker.js"></script>
  <% } %>

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta charset="utf-8"/>
  <title>Fusion Starter</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

index.js:索引.js:

import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import App from './components/App';
require('./favicon.ico'); // Tell webpack to load favicon.ico
import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import './styles/spa.less';
import './styles/jquery-ui.min.css';
import './styles/jquery-ui.structure.min.css';
import './styles/jquery-ui.theme.min.css';


const store = configureStore();

render(
  <Provider store={store}>
    <App />
  </Provider>, document.getElementById('app')
);

App.js:应用程序.js:

import React, { PropTypes } from 'react';
import Header from './common/Header';

const App = () => {
  return (
    <div>
      <Header />
      <div id="content" className="ui-front">
       <div id="appContainer">
        <div id="accordionContainer">
         <div id="accordion">
          <h3 id="accountDetailsPanel">SELECT STATE AND ACCOUNT TYPE</h3>
          <div id="accountDetailsContainer" className="inner-content"></div>
         </div>
        </div>
       </div>
      </div>
    </div>
  );
};

$(document).ready(function () {
  $("#accordion").accordion({ header: "h3",          
      autoheight: false,
      active: false,
      alwaysOpen: false,
      fillspace: false,
      collapsible: true,
//heightStyle: 'content'   //auto, fill, content
  });
});

export default App;

package.json:包.json:

{
  "name": "practice",
  "version": "0.1.0",
  "description": "",
  "engines": {
    "npm": ">=3"
  },
  "scripts": {
    "preinstall": "node tools/nodeVersionCheck.js",
    "setup": "node tools/setup/setupMessage.js && npm install && node tools/setup/setup.js",
    "remove-demo": "babel-node tools/removeDemo.js",
    "start-message": "babel-node tools/startMessage.js",
    "prestart": "npm-run-all --parallel start-message remove-dist",
    "start": "npm-run-all --parallel test:watch open:src lint:watch",
    "open:src": "babel-node tools/srcServer.js",
    "open:dist": "babel-node tools/distServer.js",
    "lint": "esw webpack.config.* src tools --color",
    "lint:watch": "npm run lint -- --watch",
    "clean-dist": "npm run remove-dist && mkdir dist",
    "remove-dist": "rimraf ./dist",
    "prebuild": "npm run clean-dist && npm run lint && npm run test",
    "build": "babel-node tools/build.js && npm run open:dist",
    "test": "mocha tools/testSetup.js \"src/**/*.spec.js\" --reporter progress",
    "test:cover": "babel-node node_modules/isparta/bin/isparta cover --root src --report html node_modules/mocha/bin/_mocha -- --require ./tools/testSetup.js \"src/**/*.spec.js\" --reporter progress",
    "test:cover:travis": "babel-node node_modules/isparta/bin/isparta cover --root src --report lcovonly _mocha -- --require ./tools/testSetup.js \"src/**/*.spec.js\" && cat ./coverage/lcov.info | node_modules/coveralls/bin/coveralls.js",
    "test:watch": "npm run test -- --watch",
    "open:cover": "npm run test:cover && open coverage/index.html"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "jquery": "3.1.0",
    "jquery-ui": "1.12.0",
    "object-assign": "4.1.0",
    "react": "15.2.0",
    "react-dom": "15.2.0",
    "react-redux": "4.4.5",
    "react-router-redux": "4.0.5",
    "redux": "3.5.2"
  },
  "devDependencies": {
    "babel-cli": "6.10.1",
    "babel-core": "6.10.4",
    "babel-loader": "6.2.4",
    "babel-plugin-react-display-name": "2.0.0",
    "babel-preset-es2015": "6.9.0",
    "babel-preset-react": "6.11.1",
    "babel-preset-react-hmre": "1.1.1",
    "babel-preset-stage-1": "6.5.0",
    "babel-register": "6.9.0",
    "browser-sync": "2.13.0",
    "chai": "3.5.0",
    "chalk": "1.1.3",
    "coveralls": "2.11.11",
    "cross-env": "1.0.8",
    "css-loader": "0.23.1",
    "enzyme": "2.4.1",
    "eslint": "3.0.1",
    "eslint-plugin-import": "1.10.2",
    "eslint-plugin-jsx-a11y": "1.5.5",
    "eslint-plugin-react": "5.2.2",
    "eslint-watch": "2.1.13",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.9.0",
    "html-webpack-plugin": "2.22.0",
    "isparta": "4.0.0",
    "less": "2.7.1",
    "less-loader": "2.2.3",
    "mocha": "2.5.3",
    "node-sass": "3.8.0",
    "npm-run-all": "2.3.0",
    "open": "0.0.5",
    "prompt": "1.0.0",
    "react-addons-test-utils": "15.2.0",
    "redux-immutable-state-invariant": "1.2.3",
    "replace": "0.3.0",
    "rimraf": "2.5.3",
    "sass-loader": "4.0.0",
    "sinon": "1.17.4",
    "sinon-chai": "2.8.0",
    "style-loader": "0.13.1",
    "url-loader": "0.5.7",
    "webpack": "1.13.1",
    "webpack-dev-middleware": "1.6.1",
    "webpack-hot-middleware": "2.12.1",
    "webpack-md5-hash": "0.0.5"
  },
  "keywords": [],
  "repository": {
    "type": "git",
    "url": ""
  }
}

webpack.config.dev.js: webpack.config.dev.js:

import webpack from 'webpack';
import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';

export default {
  debug: true,
  devtool: 'cheap-module-eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
  noInfo: true, // set to false to see a list of every file being bundled.
  entry: [
    'webpack-hot-middleware/client?reload=true',
    './src/index'
  ],
  target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
  output: {
    path: `${__dirname}/src`, // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: 'http://localhost:3000/', // Use absolute paths to avoid the way that URLs are resolved by Chrome when they're parsed from a dynamically loaded CSS blob. Note: Only necessary in Dev.
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'), // Tells React to build in either dev or prod modes. https://facebook.github.io/react/downloads.html (See bottom)
      __DEV__: true
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({     // Create HTML file that includes references to bundled CSS and JS.
      template: 'src/index.ejs',
      minify: {
        removeComments: true,
        collapseWhitespace: true
      },
      inject: true
    })
  ],
  module: {
    loaders: [
      {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
      {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
      {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff"},
      {test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=application/octet-stream'},
      {test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=image/svg+xml'},
      {test: /\.(jpe?g|png|gif)$/i, loaders: ['file']},
      {test: /\.ico$/, loader: 'file-loader?name=[name].[ext]'},
      {test: /\.css$/, loaders: ['style', 'css?sourceMap']},
      {test: /\.scss$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap']},
      {test: /\.less$/, loaders: ['style', 'css?sourceMap', 'less?sourceMap']}
    ]
  }
};

I had a similar problem and it worked for me:我有一个类似的问题,它对我有用:

new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
}),

// ...

alias: {
  jquery: 'jquery/src/jquery',
  'jquery-ui': 'jquery-ui/ui',
},

I'm still new to webpack, but https://stackoverflow.com/a/39230057/1798643 worked for me:我还是 webpack 的新手,但https://stackoverflow.com/a/39230057/1798643对我有用:

npm i -S jquery-ui-bundle

Then use:然后使用:

require("jquery-ui-bundle");

If you try to alias jquery-ui module, you're in for trouble since its in:如果您尝试为 jquery-ui 模块设置别名,则会遇到麻烦,因为它位于:

./build/release.js

Which you can alias in webpack config:你可以在 webpack 配置中别名:

alias: {
  "jquery-ui": "jquery-ui/build/release.js",
  ...

But that will lead to more trouble since its inner requires will not be resolved:但这会导致更多的麻烦,因为它的内在需求不会得到解决:

Module not found: Error: Cannot resolve module 'shelljs'
Module not found: Error: Cannot resolve module 'download.jqueryui.com/lib/jquery-ui'
Module not found: Error: Cannot resolve module 'node-packager'

And so on...等等...

I solved this issue by setting gloabl variables window.$ and window.jQuery after plugin functions were imported:我通过在导入插件函数后设置全局变量window.$window.jQuery解决了这个问题:

import $ from 'jquery';
import 'webpack-jquery-ui'
import 'webpack-jquery-ui/css'
//console.log($.ui.dialog)   //check new plugin function
window.$ = window.jQuery = $;

It also works when you need more jQuery plugin, such as jstree, datatables, eg当您需要更多 jQuery 插件,例如 jstree、datatables,例如

import $ from 'jquery';
import 'webpack-jquery-ui'
import 'jstree'
//console.log($.fn.jstree)   //check new plugin function
window.$ = window.jQuery = $;

The tip is window.$ = window.jQuery = $;提示是window.$ = window.jQuery = $; after plugin were imported.插件导入后。 Otherwise you would see $.ui.dialog is defined in main.js, but it is undefined in other script files否则你会看到 $.ui.dialog 在 main.js 中定义,但在其他脚本文件中未定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM