您正在寻找的是webpacker gem,它默认随Rails 5.1+ 提供,但可用于Rails 4.2+。进行设置,然后按照以下步骤在 Rails 应用程序中运行自定义 Modernizr 构建:
加载器
为modernizr安装加载器:
$ yarn install webpack-modernizr-loader
Modernizr 配置
从modernizr 站点下载所需的modernizr 配置。访问这样的链接:
https://modernizr.com/download?-appearance-backgroundblendmode-backgroundcliptext-backgroundsize-bgpositionxy-borderradius-boxshadow-boxsizing-canvas-canvastext-cssgradients-csspointerevents-fontface-generatedcontent-inputtypes-lastchild-mediaqueries-multiplebgs-opacity-svg-touchevents-setclasses-dontmin-cssclassprefix:mod_
然后配置你的构建,点击右上角的“Build”,下载“Command Line Config”。
然后将其从 JSON 转换为模块并保存为 config/webpack/.modernizrrc.js(注意文件名中的前导句点),如下所示:
"use strict";
module.exports = {
minify: false,
options: [
"setClasses"
],
"feature-detects": [
"test/canvas",
"test/canvastext",
"test/inputtypes",
"test/svg",
"test/touchevents",
"test/css/appearance",
"test/css/backgroundblendmode",
"test/css/backgroundcliptext",
"test/css/backgroundposition-xy",
"test/css/backgroundsize",
"test/css/borderradius",
"test/css/boxshadow",
"test/css/boxsizing",
"test/css/fontface",
"test/css/generatedcontent",
"test/css/gradients",
"test/css/lastchild",
"test/css/mediaqueries",
"test/css/multiplebgs",
"test/css/opacity",
"test/css/pointerevents"
]
};
自定义配置
接下来,创建一个自定义 webpack 配置文件为 config/webpack/custom.js:
const path = require("path");
module.exports = {
module: {
rules: [
{
loader: "webpack-modernizr-loader",
test: /\.modernizrrc\.js$/
}
]
},
resolve: {
alias: {
modernizr$: path.resolve(__dirname, "./.modernizrrc.js")
}
}
};
公开配置
让你的config/webpack/environment.js 看起来像这样:
const { environment } = require("@rails/webpacker");
const customConfig = require('./custom');
environment.config.merge(customConfig);
module.exports = environment;
导入 Modernizr
将以下行添加到app/javascript/packs/application.js:
import modernizr from 'modernizr';
加载你的包
将此添加到您的布局中:
<%= javascript_pack_tag "application", defer: true %>
瞧
在浏览器中加载您的网站,检查并确认 (a) modernizr CSS 类已添加到 DOM,并且 (b) 您在控制台中没有看到任何 webpack 编译错误。
进一步阅读
当我想在 Rails 5 应用程序中使用 webpacker 设置modernizr 时,我遇到了这个问题,看到这个问题没有答案,我自己想通了。如果你想知道这一切是如何工作的,我建议阅读webpacker 和webpack-modernizr-loader 的文档。