如何在webpacker/Rails中使用select2?

3
我一直在使用通过CDN获取的Select2。我开始将CDN迁移到使用webpacker gem。我遇到了一个困难,无法导入/需要或以任何方式包括它。所以这是我的设置:
我通过以下步骤迁移了Select2:
- 运行“yarn add select2”
以下是我的environment.js文件(这是配置文件,Webpacker用于配置WebPack):
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.append(
    'Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery',
        Popper: ['popper.js', 'default']
    })
)
module.exports = environment

environment.js

require("select2")

我尝试了各种require和其他方法,但似乎都无法运行。请给予建议。谢谢。


你能详细说明一下“似乎都不起作用”吗?在webpack输出中是否看到任何错误?在开发工具控制台上是否有任何错误?另外,你的package.json文件中有什么内容? - rossta
你的 config/webpacker.yml 文件里有什么内容? - rossta
1个回答

13

以下是我会检查的内容:

  1. Install Webpacker in your Rails project properly, per the project README. If you're starting with a Rails 6 app, this will be done by default.

  2. Add both jquery and select2:

    yarn add jquery select2 
    
  3. Add a select box to the DOM

    <select class="js-states" name="state">
      <option value="AL">Alabama</option>
      ...
      <option value="WY">Wyoming</option>
    </select>
    
  4. Import jquery, select2 and select2 css and apply to the select box when the page is loaded:

    import $ from 'jquery'
    import 'select2'
    import 'select2/dist/css/select2.css'
    
    window.addEventListener('DOMContentLoaded', () => {
      $('.js-states').select2()
    })
    
  5. For development, set compile: true in config/webpacker.yml. Running the webpack-dev-server is optional.

这是我创建此演示的步骤:https://github.com/rossta/rails6-webpacker-demo/compare/example/select2


2
这个在我的开发环境下能用,但在Heroku的生产环境下就不能用了。 - don_Bigote
你知道如何启用在Ruby JS响应中使用Select2的选项吗? - Pedro
你如何使其在 DOMContentLoaded 事件监听器之外工作? - vinay mittal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接