简体   繁体   English

如何使用 webpacker 使 Rails 6 项目中的页面可以访问 javascript 函数?

[英]How do I make javascript functions accessible to pages in a Rails 6 project using webpacker?

In a Rails project, I am trying switch from using the old Sprockets asset pipeline to using webpacker.在 Rails 项目中,我尝试从使用旧的 Sprockets 资产管道切换到使用 webpacker。 I have set up these test files:我已经设置了这些测试文件:

app/javascript/lib/foo.js应用程序/javascript/lib/foo.js

function foo() {
  console.log('foo')
}
console.log('bar')

app/javascript/packs/application.js应用程序/javascript/packs/application.js

// some standard Rails JS requires
// ...
require('lib/foo')

app/views/test/index.html app/views/test/index.html

<script>
  foo()
</script>

And in my layouts/application.html.erb I have在我的layouts/application.html.erb我有

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

When I go to that page in my browser, I see "bar" logged to my console, followed by当我在浏览器中 go 到该页面时,我看到“栏”记录到我的控制台,然后是

"ReferenceError: foo is not defined" “ReferenceError:未定义 foo”

I have tried a few different approaches to setting up my files, like using import instead of require or setting module.exports = foo or export default foo in my js file, but I haven't had any luck getting around the above error message.我尝试了几种不同的方法来设置我的文件,比如使用 import 而不是 require 或在我的 js 文件中设置module.exports = fooexport default foo ,但我没有任何运气来解决上述错误消息。

So in short, how do I move javascript files from sprockets to webpacker?简而言之,如何将 javascript 文件从 sprockets 移动到 webpacker? And if possible, how do I do so without changing my existing javascript code?如果可能的话,如何在不更改现有 javascript 代码的情况下这样做?

You'll want to export functions and modules as a named export from your application.js pack and extend the Webpack config output to designate the library name and target var (or window will also work).您需要从application.js包中将函数和模块导出为命名导出并扩展 Webpack 配置output以指定库名称和目标var (或window )。

// config/webpack/environment.js

environment.config.merge({
  output: {
    library: ['Packs', '[name]'], // exports to "Packs.application" from application pack
    libraryTarget: 'var',
  }
})

// app/javascript/packs/application.js
import foo from '../lib/foo'

export {
  foo
}
<script>
 $(document).ready(function(){
   Packs.application.foo();
 });
</script>

The library name is arbitrary. library名称是任意的。 Using the [name] placeholder is optional but allows you to export to separate modules if you're using multiple "packs".使用[name]占位符是可选的,但如果您使用多个“包”,则允许您导出到单独的模块。

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

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