目录
vue-cli3以下版本中,关于webpack的一些配置都在config目录文件中,可是vue-cli3以上版本中,没有了config目录,那该怎么配置webpack呢?
3.x初始化项目后没有了build和config文件,如果你想对webpack相关内容进行配置,需要自己在根目录下(与package.json同级)创建一个vue.config.js文件,这个文件一旦存在,那么它会被 @vue/cli-service 自动加载。(但需要我们自己手动创建哦vue.config.js,跟package.json同级)
在配置中绝大多数都是(可选项)
常规操作还是用到了commjs语法
module.exports = {
}
部署应用包的基本Url,默认/, 可以设置为相对路径./,这样打出来的包,可以部署到任意路径上
let developmentPath='./';//开发环境-npm run serve时引用文件路径
let productionPath='./';//生产环境-npm run build打包后引用文件路径
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? productionPath: developmentPath, // 基本路径-引用文件的路
}
输出文件目录(打包后生成的目录,默认dist)
module.exports = {
outputDir: __dirname + '/server/dist', //build之后静态文件输出路径
//outputDir: 'dist',
}
打包后生成的静态资源目录,默认“ ” ,也就是我们打包后的css,js等存放的位置
module.exports = {
assetsDir: 'static',
}
是否在保存的时候检查
module.exports = {
lintOnSave: process.env.NODE_ENV !== 'production',// eslint-loader
}
生产环境的 source map,可以将其设置为 false 以加速生产环境构建,默认值是true
module.exports = {
productionSourceMap: false,
}
可通过 devServer.proxy解决前后端跨域问题(反向代理)
module.exports = {
// 反向代理
devServer: {
index: '/login.html', //默认打开文件
open: true, //自动打开浏览器
host: 'localhost', //默认打开域名
port: 8080, //默认打开端口号
https: false, //开启关闭https请求
hotOnly: false, //热更
proxy: {
// 配置跨域
'/api': {
target: 'http://dev.aabb.cn:8082/', //代理地址,这里设置的地址会代替axios中设置的baseURL
ws: true, proxy websockets
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
pathRewrite: { //pathRewrite方法重写url
'^/api': '/',
},
},
},
},
}
扩展: hot 和 hotOnly 的区别是在某些模块不支持热更新的情况下,前者会自动刷新页面,后者不会刷新页面,而是在控制台输出热更新失败
module.exports = {
chainWebpack: (config) => {
config.plugins.delete('preload')
config.plugins.delete('prefetch')
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]',
})
.end()
const imagesRule = config.module.rule('images')
imagesRule.uses.clear() //清除原本的images loader配置
imagesRule
.test(/\.(jpg|gif|png|svg)$/)
.exclude.add(path.join(__dirname, '../node_modules')) //不对node_modules里的图片转base64
.end()
.use('url-loader')
.loader('url-loader')
.options({ name: 'img/[name].[hash:8].[ext]', limit: 6000000 })
config.optimization.splitChunks({
cacheGroups: {
vendors: {
name: 'chunk-vendors',
minChunks: pageNum,
test: /node_modules/,
priority: -10,
chunks: 'initial',
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true,
},
},
})
},
}
扩展:
Preload: 用于标记页面加载后即将用到的资源,浏览器将在主体渲染前加载preload标记文件。Vue CLI 应用会为所有初始化渲染需要的文件自动生成 preload 提示;
Prefetch: 用于标记浏览器在页面加载完成后,利用空闲时间预加载的内容。Vue CLI 应用默认为所有作为 async chunk 生成的 JavaScript 文件 (通过动态 import() 按需 code splitting 的产物) 自动生成prefetch提示。
webpack配置
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const Version = 'V6.1'
const Timestamp = new Date().getTime()
module.exports = {
webpack配置
configureWebpack: (config) => {
// 为生产环境修改配置
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,//生产环境自动删除debugger
drop_console: true, //生产环境自动删除console
},
warnings: false,
},
sourceMap: false, //关掉sourcemap 会生成对于调试的完整的.map文件,但同时也会减慢打包速度
parallel: true, //使用多进程并行运行来提高构建速度。默认并发运行数:os.cpus().length - 1。
}),
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8,
})
)
}
// 在这里配置后,减少了压缩的包内容,需要在public/index.html通过cdn方式再引入,注意对应的版本
config.externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios',
jquery: '$',
moment: 'moment',
'mint-ui': 'MINT'
},
// 别名配置
Object.assign(config, {
// 开发生产共同配置
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@c': path.resolve(__dirname, './src/components'),
'@p': path.resolve(__dirname, './src/pages')
}
}
}),
config.output.filename = `[name].${Version}.${Timestamp}.js` //打包生成的文件
config.output.chunkFilename = `[name].${Version}.${Timestamp}.js`
},
}
扩展:
entry:{
main:__dirname + '/app/main.js',
index:__dirname + '/app/index.js'
},
output:{
path:__dirname + '/public', //通过HtmlWebpackPlugin插件生成的html文件存放在这个目录下面
filename:'/js/[name].js', //编译生成的js文件存放到根目录下面的js目录下面,如果js目录不存在则自动创建
/*
* chunkFilename用来打包require.ensure方法中引入的模块,如果该方法中没有引入任何模块则不会生成任何chunk块文件
* 比如在main.js文件中,require.ensure([],function(require){alert(11);}),这样不会打包块文件
* 只有这样才会打包生成块文件require.ensure([],function(require){alert(11);require('./greeter')})
* 或者这样require.ensure(['./greeter'],function(require){alert(11);})
* chunk的hash值只有在require.ensure中引入的模块发生变化,hash值才会改变
* 注意:对于不是在ensure方法中引入的模块,此属性不会生效,只能用CommonsChunkPlugin插件来提取
* */
chunkFilename:'js/[chunkhash:8].chunk.js'
},
configureWebpack和chainWebpack区别
在这里configureWebpack和chainWebpack的作用相同,唯一的区别就是他们修改webpack配置的方式不同:
这里配置了全局sass 需要安装的依赖 sass-loader less-loader
css: {
loaderOptions: {
scss: {
additionalData: `@import "@/assets/css/reset.scss";@import "@/assets/css/globle.scss";` //注意配置的键名
},
postcss: {
plugins: [
//remUnit这个配置项的数值是多少呢??? 通常我们是根据设计图来定这个值,原因很简单,便于开发。
//假如设计图给的宽度是750,我们通常就会把remUnit设置为75,这样我们写样式时,可以直接按照设计图标注的宽高来1:1还原开发。
require('postcss-px2rem')({
remUnit: 37.5
})
]
}
}
},
由于 sass-loader 版本不同,loaderOptions 中的 additionalData 的键名也不同
vue-cli3中的webpack与vue多页面应用开发
相关参数:
module.exports = {
pages:{
main: {
// page 的入口
entry: "src/pages/main/main.js",
// 模板来源
template: "public/index.html",
// 在 dist/index.html 的输出
filename: "main.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "Index Page",
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ["chunk-vendors", "chunk-common", "main"]
},
hh: {
// page 的入口
entry: "src/pages/login/main.js",
// 模板来源
template: "public/index.html",
// 在 dist/index.html 的输出
filename: "login.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "Index Page",
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ["chunk-vendors", "chunk-common", "hh"]
},
// 当使用只有入口的字符串格式时,
// 模板会被推导为 `public/subpage.html`
// 并且如果找不到的话,就回退到 `public/index.html`。
// 输出文件名会被推导为 `subpage.html`。
subpage: "src/subpage/main.js"
},
}
封装
const glob = require('glob') // 引入glob模块,用于扫描全部src/pages/**/main.js(返回的是一个数组)
// 打包多入口文件基本配置
function getPagesInfo() {
let pages = {}
glob.sync('src/pages/**/main.js').forEach((entry, i) => {
let name = entry.slice(10, -8)
pages[name] = {
entry: entry,
template: 'public.index.html',
filename: name + '.html',
title: '',
chunks: ["chunk-vendors", "chunk-common", name]
}
})
return pages
}
module.exports = {
pages: getPagesInfo(),
publicPath: './kk',
assetsDir: 'static',
};
当运行项目并且打包的时候,会发现chunk-vendors.js这个文件非常大,那是因为webpack将所有的依赖全都压缩到了这个文件里面,这时我们可以将其拆分,将所有的依赖都打包成单独的js;
/*
利用splitChunks将每个依赖包单独打包,在生产环境下配置,代码如下
*/
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production'
// 将每个依赖包打包成单独的js文件
let optimization = {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 20000, // 依赖包超过20000bit将被单独打包
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name (module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`
}
}
}
}
}
Object.assign(config, {
optimization
})
}
}
上面已经提到过去掉打印的操作(console、debug)这里详细讲解一下
首先下载相关插件 uglifyjs-webpack-plugin
npm i -D uglifyjs-webpack-plugin
在vue.config.js文件中引入,并在configureWebpack的optimization中添加如下代码
const UglifyPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production'
// 将每个依赖包打包成单独的js文件
let optimization = {
/*以下代码适用于uglifyjs-webpack-plugin 2.1.1及以前的版本*/
minimizer: [new UglifyPlugin({
uglifyOptions: {
compress: {
warnings: false,
drop_console: true, // console
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}
})]
}
Object.assign(config, {
optimization
})
}
}
}
新版uglifyjs-webpack-plugin需写成以下方式
minimizer: [new UglifyPlugin({
uglifyOptions: {
warnings: false,
compress: {
drop_console: false, // console
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}
})]
gizp压缩是一种http请求优化方式,通过减少文件体积来提高加载速度。html、js、css文件甚至json数据都可以用它压缩,可以减小60%以上的体积。webpack在打包时可以借助 compression webpack plugin 实现gzip压缩。
下载 compression webpack plugin
npm i -D compression-webpack-plugin
vue.config.js配置
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production';
if(openGzip){
config.plugins = [
...config.plugins,
new CompressionPlugin({
test:/\.js$|\.html$|.\css/, //匹配文件名
threshold: 10240,//对超过10k的数据压缩
deleteOriginalAssets: false //不删除源文件
})
]
}
} else {
// 为开发环境修改配置...
config.mode = 'development';
}
}
}
{
"name": "demo-cli3",
"version": "1.0.0",
"openGizp": false,
...
}
下载image-webpack-loader
npm install --save-dev image-webpack-loader
在vue.config.js中修改相关配置
4M的图片使用默认设置压缩成1.4M,自定义的设置可以更小
module.exports = {
...
// 默认设置
const defaultOptions = {
bypassOnDebug: true
}
// 自定义设置
const customOptions = {
mozjpeg: {
progressive: true,
quality: 50
},
optipng: {
enabled: true,
},
pngquant: {
quality: [0.5, 0.65],
speed: 4
},
gifsicle: {
interlaced: false,
},
// 不支持WEBP就不要写这一项
webp: {
quality: 75
}
}
chainWebpack: config => {
config.module.rule('images')
.test(/\.(gif|png|jpe?g|svg)$/i)
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options(customOptions)
.end()
}
}
npm i -S lib-flexible postcss-px2rem
在项目入口中main.js 中引入lib-flexible
import 'lib-flexible'
# 注意事项: 由于flexible会动态给页面header中添加<meta name='viewport' >标签,所以务必请把目录 public/index.html 中的这个标签删除!!
项目中vue.config.js中进行如下的配置
module.exports = {
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [ require('postcss-px2rem')({ remUnit: 37.5 })
]
}
}
}
}
1. 创建项目
和我们正常创建项目相同,这里通过vue-cli3脚手架进行创建
vue create 项目name
选择自己需要的依赖并进行下一步
2. 搭建文件结构
3. 配置路由
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
// return originalPush.call(this, location).catch((err) => err)
// }
const routes = [
{
path: '/login',
name: 'login',
component: () => import('./views/index.vue'),
// component:()=>import('./reset.vue'),
meta: {
title: '这里是动态title'
},
children: [
/*
单页面应用的写法
{
path: 'reset',
name: 'reset',
component: () => import('./reset.vue')
},
*/
// ***多页面的写法
{
path: 'editJobs',
components: {
'editJobs': () => import('./views/reset.vue'),
},
},],
},
// {
// path: '/',
// redirect: '/'
// }
]
export default new VueRouter({
mode: 'hash',
base: process.env.BASE_URL,
routes
})
4. 配置vue.config.js
// 打包多入口文件基本配置
function getPagesInfo() {
let pages = {}
const glob = require('glob') // 引入glob模块,用于扫描全部src/pages/**/main.js(返回的是一个数组)
glob.sync('src/pages/**/main.js').forEach((entry, i) => {
let name = entry.slice(10, -8)
pages[name] = {
entry: entry,
template: 'public.index.html',
filename: name + '.html',
title: '',
chunks: ["chunk-vendors", "chunk-common", name]
}
})
return pages
}
module.exports = {
pages: getPagesInfo(),
publicPath: './kk',
assetsDir: 'static',
};
npm i -S vue-wechat-title
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
<template>
<!-- 动态设置title -->
<div id="app" v-wechat-title='$route.meta.title'>
<router-view/>
</div>
</template>
const routes = [
{
path: '/login',
name: 'login',
component: () => import('./views/index.vue'),
meta: {
title: '这里是动态title'
},
children: [
// ***多页面的写法
{
path: 'editJobs',
components: {
'editJobs': () => import('./views/reset.vue'),
},
},],
},
]
<template>
<div>
login
<router-link :to="{ name: 'reset' }" tag="li">我的收藏</router-link>
这里的name对应的是route配置里的名字(别忘了地址连里面的path)
<router-view name="editJobs">待完善信息</router-view>
</div>
</template>
// 打包多入口文件基本配置
let developmentPath = './';//开发环境-npm run serve时引用文件路径
let productionPath = './';//生产环境-npm run build打包后引用文件路径
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')//生产环境取消打印
const CompressionWebpackPlugin = require('compression-webpack-plugin')//gzip压缩
const productionGzipExtensions = ['js', 'css']
const Version = 'V6.1'
const Timestamp = new Date().getTime()
function getPagesInfo() {
let pages = {}
const glob = require('glob') // 引入glob模块,用于扫描全部src/pages/**/main.js(返回的是一个数组)
glob.sync('src/pages/**/main.js').forEach((entry, i) => {
let name = entry.slice(10, -8)
pages[name] = {
entry: entry,
template: 'public.index.html',
filename: name + '.html',
title: '',
chunks: ["chunk-vendors", "chunk-common", name]
}
})
return pages
}
// 打包相关
module.exports = {
pages: getPagesInfo(),//多页面应用配置
publicPath: process.env.NODE_ENV === 'production' ? productionPath : developmentPath, // 基本路径-引用文件的路 __dirname + '/server/dist', //build之后静态文件输出路径
assetsDir: 'static',//静态资源大包位置
outputDir: __dirname + '/server/dist', //build之后静态文件输出路径
lintOnSave: process.env.NODE_ENV !== 'production',// 打包的时候eslint-loader检查
productionSourceMap: false,//source map 检查
// 启动服务器
devServer: {
index: '/login.html', //默认打开文件
open: true, //自动打开浏览器
host: 'localhost', //默认打开域名
port: 8080, //默认打开端口号
https: false, //开启关闭https请求
hotOnly: false, //热更
// 反向代理
proxy: {
// 配置跨域
'/api': {
target: 'http://dev.aabb.cn:8082/', //代理地址,这里设置的地址会代替axios中设置的baseURL
ws: true, proxy websockets
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
pathRewrite: { //pathRewrite方法重写url
'^/api': '/',
},
},
},
},
// webpack配置 链式
chainWebpack: (config) => {
// 1、取消预加载增加加载速度
config.plugins.delete('preload')
config.plugins.delete('prefetch')
// 2、vue中使用SVG图标,并且想批量导入,然后需要使用的时候直接添加就可以
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]',
})
.end()
// 3、图片处理
const imagesRule = config.module.rule('images')
imagesRule.uses.clear() //清除原本的images loader配置
imagesRule
.test(/\.(jpg|gif|png|svg)$/)
.exclude.add(path.join(__dirname, '../node_modules')) //不对node_modules里的图片转base64
.end()
.use('url-loader')
.loader('url-loader')
.options({ name: 'img/[name].[hash:8].[ext]', limit: 6000000 })
config.optimization.splitChunks({
cacheGroups: {
vendors: {
name: 'chunk-vendors',
minChunks: pageNum,
test: /node_modules/,
priority: -10,
chunks: 'initial',
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true,
},
},
})
},
// webpack配置
configureWebpack: (config) => {
// 为生产环境修改配置
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
// 1、取消打印
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,//生产环境自动删除debugger
drop_console: true, //生产环境自动删除console
},
warnings: false,
},
sourceMap: false, //关掉sourcemap 会生成对于调试的完整的.map文件,但同时也会减慢打包速度
parallel: true, //使用多进程并行运行来提高构建速度。默认并发运行数:os.cpus().length - 1。
}),
// 2、gzip压缩
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8,
})
)
}
// 在这里配置后,减少了压缩的包内容,需要在public/index.html通过cdn方式再引入,注意对应的版本
config.externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios',
jquery: '$',
moment: 'moment',
'mint-ui': 'MINT'
},
// 别名配置
Object.assign(config, {
// 开发生产共同配置
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@c': path.resolve(__dirname, './src/components'),
'@p': path.resolve(__dirname, './src/pages')
}
}
}),
config.output.filename = `[name].${Version}.${Timestamp}.js` //打包生成的文件
config.output.chunkFilename = `[name].${Version}.${Timestamp}.js`
},
// css相关
css: {
loaderOptions: {
// 配置全局sass
scss: {
additionalData: `@import "@/assets/css/reset.scss";@import "@/assets/css/globle.scss";` //注意配置的键名
},
// lib-flexible
postcss: {
plugins: [
//remUnit这个配置项的数值是多少呢??? 通常我们是根据设计图来定这个值,原因很简单,便于开发。
//假如设计图给的宽度是750,我们通常就会把remUnit设置为75,这样我们写样式时,可以直接按照设计图标注的宽高来1:1还原开发。
require('postcss-px2rem')({
remUnit: 37.5
})
]
}
}
},
parallel: require('os').cpus().length > 1, // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
pwa: {}, // PWA 插件相关配置
pluginOptions: {}, // 第三方插件配置
}; 我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr