簡體   English   中英

如何將 jQuery 添加到 Mastodon(使用 Rails 6 和 Webpacker 4)?

[英]How do I add jQuery to Mastodon (using Rails 6 and Webpacker 4)?

我從 2020 年開始關注這個問題如何在 Rails 6.0.3.3 中使用 jQuery? ,但我無法將 jQuery 添加到 Mastodon 中的 Rails 6 和 Webpacker 4 https://github.com/mastodon/mastodon但是,我可以添加一個 custom.js 文件來加載我的 jQuery function; 這是未加載的主要 jQuery 庫。

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.jsonyarn.lock中。

我將require('jquery')添加到 app/javascript/packs/application.js:

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') // custom.js file I added

但是我在 Mastodon 站點文件中沒有 environment.js 文件,並且不存在的 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

我退出根帳戶並運行

systemctl restart mastodon-*

我在控制台中測試了 jQuery,但它沒有加載:

在此處輸入圖像描述

但是, packs/custom.js文件正在加載,因為它包含

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

我看到custom js is loaded到控制台中。

有任何想法嗎? 為什么 jQuery 沒有加載?

  1. environment.js文件文件在哪里?

  2. 通知warning Workspaces can only be enabled in private projects是一個嚴重的錯誤嗎?

  3. 我已經運行RAILS_ENV=production bundle exec rails assets:clobber來清除 Webpacker,但這對缺少 jQuery 庫沒有幫助。

編輯 23 年 1 月 25 日:

根據 mechnicov 的回答,這是 /config/webpack/ 中的 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,
  },
};

如果您的 package.json 中沒有,請先添加package.json

yarn add jquery

如我所見,Mastodon 有webpack

你可以使用它在項目中安裝 JQuery

為此,您可以將更改添加到config/webpack/shared.jsconfig/webpack/configuration.js

可能第一個文件更好。 因為那里安裝了插件並且webpack 導入已經存在

但是您也可以根據需要使用第二個文件

最后你需要添加到plugins數組這樣的元素

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM