[英]How do I use jquery datetimepicker with webpacker in rails 6
[英]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.json
和yarn.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 没有加载?
environment.js文件文件在哪里?
通知warning Workspaces can only be enabled in private projects
是一个严重的错误吗?
我已经运行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.js
或config/webpack/configuration.js
可能第一个文件更好。 因为那里安装了插件并且webpack 导入已经存在
但是您也可以根据需要使用第二个文件
最后你需要添加到plugins
数组这样的元素
new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.