ruby-on-rails 在Rails 7应用程序的esbuild中捆绑目录结构

xytpbqjk  于 2023-05-23  发布在  Ruby
关注(0)|答案(1)|浏览(190)

如何导入带有目录的Javascript?
我已经使用esbuild bundler为一个Rails 7项目设置了jsbundling-rails,该项目以前使用sprocket来处理所有资产。看起来我已经正确地设置了它,因为我可以通过直接引用文件来加载JS文件。
虽然我有很多文件,我甚至想在javascript的结构上强加一些人类逻辑。
为此,我想在目录中分割一些javascript,如下所示:

app
- assets
-- javascript
--- some.js
--- some_more.js
---- base
----- some_other.js
----- some_way_other.js

我可以用我的application.jsapp/assets/javascript/application.js文件中加载所有这些js,像这样:

import "./some"
import "./some_more"
import "./base/some_other"
import "./base/some_way_other"

控制台日志响应如下:

但我希望能够使用以下语法加载/绑定此JS:

import "./some"
import "./some_more"
import "./base"

但是从js watcher中,我得到:

15:39:22 js.1   | [watch] build started (change: "app/javascript/application.js")
15:39:22 js.1   | ✘ [ERROR] Could not resolve "./base"
15:39:22 js.1   |
15:39:22 js.1   |     app/javascript/application.js:14:7:
15:39:22 js.1   |       14 │ import "./base"
15:39:22 js.1   |          ╵        ~~~~~~~~
15:39:22 js.1   |
15:39:22 js.1   | 1 error
15:39:22 js.1   | [watch] build finished

我的www.example.com Procfile.dev

web: unset PORT && /root/.rbenv/shims/thin start -C config/thin_development.yml
js: yarn build --watch

我是说,这可能吗?我曾经能够做到这一点与链轮,但它似乎不像我可以与esbuild。或者我应该坚持使用一个庞大的application.js文件,然后手动导入每个javascript文件?

lf3rwulv

lf3rwulv1#

实现此目的的方法是使用名为esbuild.config.js的配置文件自定义esbuild,并利用Chris在GoRails上创建的插件esbuild-rails,该插件位于https://github.com/excid3/esbuild-rails
esbuild.config.js

const path = require('path');
const rails = require('esbuild-rails')

const watch = process.argv.includes("--watch") && {
  onRebuild(error) {
    if (error) console.error("[watch] build failed", error);
    else console.log("[watch] build finished");
  },
};

require("esbuild").build({
  entryPoints: ["application.js"],
  bundle: true,
  minify: true,
  outdir: path.join(process.cwd(), "app/assets/builds"),
  absWorkingDir: path.join(process.cwd(), "app/javascript"),
  watch: watch,
  write: true,
  loader: { '.js': 'jsx' },
  publicPath: 'assets',
  target: 'es6',
  // custom plugins will be inserted is this array
  plugins: [rails()],
}).catch(() => process.exit(1));

application.js中的用法

import { Application } from "@hotwired/stimulus"
const application = Application.start()

import './meta/jquery'
import './meta/ajax'
import './controllers'

import libraries from "./libraries/*.js"
import custom_files from "./custom/*.js"

libraries.forEach((controller) => {
    application.register(controller.name, controller.module.default)
})

custom_files.forEach((controller) => {
    application.register(controller.name, controller.module.default)
})

相关问题