You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mastodon 4.02(基于Rails 6和Webpacker 4)中引入jQuery?

在Mastodon 4.0.2(基于Rails 6 + Webpacker 4)中引入jQuery失败的问题

编辑于2023年1月27日

核心问题:

  • 为何找不到environment.js文件?是否和Webpacker 4有关?
  • 尝试两种直接在app/views/layouts/application.html.haml中加载jQuery的方式均失败,触发Mastodon通用错误页面,且journalctl -u mastodon-web无报错信息:
    • 使用= javascript_pack_tag 'jquery-min'加载app/javascript/packs/jquery-min.js(该文件为jQuery库文件)
    • 使用= javascript_include_tag "https://code.jquery.com/jquery-3.6.6.min.js"

原始问题

在Mastodon:~/live$下执行yarn add jquery,返回结果如下:

yarn add v1.22.19
[1/6] Validating package.json...
[2/6] Resolving packages...
[3/6] Fetching packages...
[4/6] Linking dependencies...
warning Workspaces can only be enabled in private projects.
[5/6] Building fresh packages...
[6/6] Cleaning modules...
warning Workspaces can only be enabled in private projects.
success Saved 1 new dependency.
info Direct dependencies
└─ jquery@3.6.3
info All dependencies
└─ jquery@3.6.3
Done in 24.18s.

可确认jQuery已成功添加到package.json和yarn.lock中。

在app/javascript/packs/application.js中添加了require('jquery'),修改后的代码如下:

import './public-path';
import loadPolyfills from '../mastodon/load_polyfills';
import { start } from '../mastodon/common';

start();

loadPolyfills().then(async () => {
  const { default: main } = await import('mastodon/main');

  return main();
}).catch(e => {
  console.error(e);
});

require('jquery')
require('packs/custom') // 我添加的自定义js文件

但Mastodon项目中没有参考资料提到的environment.js文件,该文件原本应包含以下配置:

const { environment } = require("@rails/webpacker");
const webpack = require("webpack");

environment.plugins.append(
  "Provide",
  new webpack.ProvidePlugin({
    $: "jquery/src/jquery",
    jQuery: "jquery/src/jquery",
  })
);

module.exports = environment;

执行了以下命令:

RAILS_ENV=production bundle exec rake tmp:cache:clear
RAILS_ENV=production bundle exec rails assets:generate_static_pages

接着执行预编译命令:

RAILS_ENV=production bundle exec rails assets:precompile

返回结果:

yarn install v1.22.19
[1/6] Validating package.json...
[2/6] Resolving packages...
[3/6] Fetching packages...
[4/6] Linking dependencies...
warning Workspaces can only be enabled in private projects.
[5/6] Building fresh packages...
[6/6] Cleaning modules...
Done in 18.17s.
Everything's up-to-date. Nothing to do

退出root账户后重启服务:
systemctl restart mastodon-*

在浏览器控制台测试发现jQuery未加载,但自定义的packs/custom.js已成功加载,该文件内容为:

console.log("custom js is loaded");

控制台能正常输出custom js is loaded。

疑问

  1. environment.js文件在哪里?
  2. warning Workspaces can only be enabled in private projects这个警告是否属于严重错误?
  3. 已执行RAILS_ENV=production bundle exec rails assets:clobber清理Webpacker缓存,但仍无法解决jQuery未加载的问题。

编辑于2023年1月25日

根据mechnicov的建议,在/config/webpack/shared.js中添加了new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" }),但问题依旧。修改后的shared.js代码如下:

const webpack = require('webpack');
const { basename, dirname, join, relative, resolve } = require('path');
const { sync } = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const AssetsManifestPlugin = require('webpack-assets-manifest');
const extname = require('path-complete-extname');
const { env, settings, themes, output } = require('./configuration');
const rules = require('./rules');
const localePackPaths = require('./generateLocalePacks');

const extensionGlob = `**/*{${settings.extensions.join(',')}}*`;
const entryPath = join(settings.source_path, settings.source_entry_path);
const packPaths = sync(join(entryPath, extensionGlob));

module.exports = {
  entry: Object.assign(
    packPaths.reduce((map, entry) => {
      const localMap = map;
      const namespace = relative(join(entryPath), dirname(entry));
      localMap[join(namespace, basename(entry, extname(entry)))] = resolve(entry);
      return localMap;
    }, {}),
    localePackPaths.reduce((map, entry) => {
      const localMap = map;
      localMap[basename(entry, extname(entry, extname(entry)))] = resolve(entry);
      return localMap;
    }, {}),
    Object.keys(themes).reduce((themePaths, name) => {
      themePaths[name] = resolve(join(settings.source_path, themes[name]));
      return themePaths;
    }, {}),
  ),

  output: {
    filename: 'js/[name]-[chunkhash].js',
    chunkFilename: 'js/[name]-[chunkhash].chunk.js',
    hotUpdateChunkFilename: 'js/[id]-[hash].hot-update.js',
    hashFunction: 'sha256',
    path: output.path,
    publicPath: output.publicPath,
  },

  optimization: {
    runtimeChunk: {
      name: 'common',
    },
    splitChunks: {
      cacheGroups: {
        default: false,
        vendors: false,
        common: {
          name: 'common',
          chunks: 'all',
          minChunks: 2,
          minSize: 0,
          test: /^(?!.*[\\\\/node_modules[\\\\/react-intl[\\\\/]).+$/, 
        },
      },
    },
    occurrenceOrder: true,
  },

  module: {
    rules: Object.keys(rules).map(key => rules[key]),
  },

  plugins: [

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

    new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(env))),
    new webpack.NormalModuleReplacementPlugin(
      /^history\//, (resource) => {
        // temporary fix for https://github.com/ReactTraining/react-router/issues/5576
        // to reduce bundle size
        resource.request = resource.request.replace(/^history/, 'history/es');
      },
    ),
    new MiniCssExtractPlugin({
      filename: 'css/[name]-[contenthash:8].css',
      chunkFilename: 'css/[name]-[contenthash:8].chunk.css',
    }),
    new AssetsManifestPlugin({
      integrity: true,
      integrityHashes: ['sha256'],
      entrypoints: true,
      writeToDisk: true,
      publicPath: true,
    }),
  ],

  resolve: {
    extensions: settings.extensions,
    modules: [
      resolve(settings.source_path),
      'node_modules',
    ],
  },

  resolveLoader: {
    modules: ['node_modules'],
  },

  node: {
    // Called by http-link-header in an API we never use, increases
    // bundle size unnecessarily
    Buffer: false,
  },
};

内容的提问来源于stack exchange,提问作者user5853892

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:50:34