简体   繁体   English

使用create-react-app时包括jquery库(包括CSS)的正确方法是什么?

[英]What is the correct way to include jquery libraries including CSS when using create-react-app?

I'm trying to utilize a jquery library called select2 in my React app created by create-react-app. 我正在尝试在由create-react-app创建的React应用中利用一个名为select2的jQuery库。

I have added jquery and select2 to my package.json and I can make the javascript work. 我已经将jquery和select2添加到我的package.json中,并且可以使JavaScript工作。

However, the styling does not work as the css file of select 2 is not included correctly. 但是,样式不起作用,因为未正确包含选择2的css文件。

I can see the following file inside my project: 我可以在项目中看到以下文件:

node_modules/select2/dist/css/select2.min.css

and of course I can copy the file into public/css and add this to my index.html: 当然,我可以将文件复制到public / css并将其添加到index.html中:

<link href="css/select2.min.css" rel="stylesheet">

I'm sure there is a better way utilizing the power of webpack and the create-react-app toolchain. 我敢肯定,有一种更好的方法可以利用webpack和create-react-app工具链的功能。 But how? 但是如何?

I often just require the css in the index of my app. 我经常只需要在我的应用程序索引中使用css。

index.js: require('node_modules/select2/dist/css/select2.min.css') index.js: require('node_modules/select2/dist/css/select2.min.css')

I think a better way is to "import" the CSS into the .js file that references your jquery library: 我认为更好的方法是将CSS“导入”到引用您的jquery库的.js文件中:

import 'select2/dist/css/select2.min.css';

That way, the CSS will be included in the bundle.js file that is generated, and you have "localized" this dependency to the code that requires it. 这样,CSS将包含在生成的bundle.js文件中,并且您已经将此依赖项“本地化”为需要它的代码。

On a related note: you may wish to Google "react select" and explore the many libraries that provide a more "React-ish" way of implementing a widget. 与此相关的是:您可能希望Google进行“反应选择”,并探索许多库,这些库提供了更多的“反应式”方式来实现小部件。

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

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