vue.config.js配置

Vue.config.js配置

vue.config.js是Vue项目的配置文件,用于配置项目的构建、打包和开发环境等。

在Vue CLI 3.0之后,项目的配置文件从原来的build和config目录下的多个配置文件,合并成了一个vue.config.js文件。这个文件可以放在项目的根目录下,用于配置项目的构建、打包和开发环境等。

官方文档

首先我们先说一下他的作用:

  1. 配置webpack相关的配置项,如入口、出口、loader、插件等;
  2. 配置开发服务器的相关配置,如端口号、是否启用https、是否自动打开浏览器以及代理配置等;
  3. 配置静态资源目录、生产环境的source map等;
  4. 配置第三方插件等。

基础配置

publicPath

​ 设置构建好的文件被部署后的公共路径

module.exports = {
	publicPath: ‘/',
};

outputDir

构建输出的目录,默认是 dist

module.exports = {
	outputDir: 'dist',
};

assetsDir

用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)

module.exports = {
	assetsDir: "static",
};

indexPath

指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径。默认 'index.html'

module.exports = {
	indexPath: "index.html",
};

productionSourceMap

如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。

module.exports = {
	productionSourceMap: false,
};

filenameHashing

默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存。然而,这也要求 index 的 HTML 是被 Vue CLI 自动生成的。如果你无法使用 Vue CLI 生成的 index HTML,你可以通过将这个选项设为 false 来关闭文件名哈希。默认 false

module.exports = {
	filenameHashing: false,
};

lintOnSave

  • 是否开启 eslint 保存检测,有效值:ture | false | 'error'
  • 设置为 true'warning' 时,eslint-loader 会将 lint 错误输出为编译警告。默认情况下,警告仅仅会被输出到命令行,且不会使得编译失败。
  • 如果你希望让 lint 错误在开发时直接显示在浏览器中,你可以使用 lintOnSave: 'default'。这会强制 eslint-loaderlint 错误输出为编译错误,同时也意味着 lint 错误将会导致编译失败。
  • 设置为 error 将会使得 eslint-loaderlint 警告也输出为编译错误,这意味着 lint 警告将会导致编译失败。
  • 设置 false 关闭 lint 警告
module.exports = {
	lintOnSave: false,
};

runtimeCompiler

  • 是否使用包含运行时编译器的 Vue 构建版本。设置为 true 后你就可以在 Vue 组件中使用 template 选项了,但是这会让你的应用额外增加 10kb 左右。默认 false
module.exports = {
	runtimeCompiler: false,
};

transpileDependencies

默认情况下 babel-loader 会忽略所有 node_modules 中的文件。你可以启用本选项,以避免构建后的代码中出现未转译的第三方依赖

不过,对所有的依赖都进行转译可能会降低构建速度。如果对构建性能有所顾虑,你可以只转译部分特定的依赖:给本选项传一个数组,列出需要转译的第三方包包名或正则表达式即可

module.exports = {
	transpileDependencies: false,
};

crossorigin

设置生成的 HTML 中 标签的 crossorigin 属性

需要注意的是该选项仅影响由 html-webpack-plugin 在构建时注入的标签 - 直接写在模版 (public/index.html) 中的标签不受影响。

crossorigin: 如果配置了该属性,会让浏览器启用CORS检查(判断响应头中Access-Control-Allow-Origin是否与当前文档同源),如果检查不通过,则浏览器拒绝执行代码。

stylesheet: 导入样式表。link 标签使用了 rel="stylesheet" 表示该文件是一份样式表文件。可以让 HTML 页面具有更好的外观和布局。

module.exports = {
	crossorigin: false,
};

integrity

  • 在生成的 HTML 中的 标签上启用 Subresource Integrity (SRI)。如果你构建后的文件是部署在 CDN 上的,启用该选项可以提供额外的安全性。
  • 需要注意的是该选项仅影响由 html-webpack-plugin 在构建时注入的标签 - 直接写在模版 (public/index.html) 中的标签不受影响。
  • 当启用 SRI 时,preload resource hints 会被禁用,因为 Chrome 的一个 bug 会导致文件被下载两次
module.exports = {
	integrity: false,
};

configureWebpack

  • 如果这个值是一个对象,则会通过 w[]ebpack-merge](https://github.com/survivejs/webpack-merge) 合并到最终的配置中。
  • 如果这个值是一个函数,则会接收被解析的配置作为参数。该函数既可以修改配置并不返回任何东西,也可以返回一个被克隆或合并过的配置版本。更多细节请查阅 配合 webpack > 简单的配置方式
module.exports = {
	configureWebpack: {}, // ()=> {}
};

chainWebpack

  • 是一个函数,会接收一个基于 webpack-chain 的 ChainableConfig 实例。允许对内部的 webpack 配置进行更细粒度的修改。更多细节可查阅:配合 webpack > 链式操作
module.exports = {
	chainWebpack: ()=> {}
};

css.modules

从 v4 起已弃用,请使用 css.requireModuleExtension。 在 v3 中,这个选项含义与 css.requireModuleExtension 相反

module.exports = {
	css: {
		modules: false,
	}
};

pages

  • 定义多个入口页面。
module.exports = {
  // 配置多页面入口
  pages: {
    index: { // 默认入口
      // page 的入口
      entry: 'src/index/main.js',
      // 模板来源
      template: 'public/index.html',
      // 在 dist/index.html 的输出
      filename: 'index.html',
      // 当使用 title 选项时,
      // template 中的 <title> 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Index Page',
      // 片段注入到页面的地点,
      // 可以是 (head / end / body / top / bottom)
      chunks: ['chunk-vendors', 'chunk-common', 'index']
    },
    otherpage: { // 新增的入口
      // page 的入口
      entry: 'src/otherpage/main.js',
      // 模板来源
      template: 'public/otherpage.html',  // 或者 'public/otherpage/otherpage.html'
      // 在 dist/otherpage.html 的输出
      filename: 'otherpage.html',
      // 当使用 title 选项时,
      // template 中的 <title> 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Other Page',
      // 片段注入到页面的地点,
      // 可以是 (head / end / body / top / bottom)
      chunks: ['chunk-vendors', 'chunk-common', 'otherpage']
    }
  }
}

参考链接: vue.config.js 配置多入口文件

配置 configureWebpack 和 chainWebpack

configureWebpack

configureWebpack 允许你在 Vue CLI 项目中直接修改 Webpack 的配置。它可以通过一个对象或一个函数来实现。如果你使用的是一个函数,那么它会接收默认的 Webpack 配置作为参数,并且你应该返回一个修改过的配置对象。

const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const WebpackObfuscator = require('webpack-obfuscator');

function resolve(dir) {
  return path.join(__dirname, dir);
}
const name = '浏览器网页标题';
module.exports = {
	configureWebpack: (config) => {
	    config.name = name,
	      config.resolve = {
	        ...config.resolve,
	        alias: {
	          "@": resolve("src"), // 配置别名 @
	          'vue': path.resolve(__dirname, './', 'node_modules', 'vue') // 去重vue包,多个vue包会导致element-ui 里的 table 组件不生效
	        }
	      },
	      config.optimization = {
	        ...config.minimizer,
	        minimizer: [
	          new TerserPlugin({
	            terserOptions: {
	              compress: {
	                drop_console: true, // 去除 console.log
	                drop_debugger: true, // 去除 debugger
	              },
	            },
	          }),
	        ]
	      }
	
	    if (process.env.NODE_ENV === 'production') {
	      config.plugins.push(
	        new WebpackObfuscator({
	          // 压缩代码
	          compact: true,
	          // 是否启用控制流扁平化(降低1.5倍的运行速度)
	          controlFlowFlattening: false,
	          // 随机的死代码块(增加了混淆代码的大小)
	          deadCodeInjection: false,
	          // 此选项几乎不可能使用开发者工具的控制台选项卡
	          debugProtection: false,
	          // 如果选中,则会在“控制台”选项卡上使用间隔强制调试模式,从而更难使用“开发人员工具”的其他功能。
	          debugProtectionInterval: false,
	          // 通过用空函数替换它们来禁用console.log,console.info,console.error和console.warn。这使得调试器的使用更加困难。
	          disableConsoleOutput: true,
	          // 标识符的混淆方式 hexadecimal(十六进制) mangled(短标识符)
	          identifierNamesGenerator: 'hexadecimal',
	          log: false,
	          // 是否启用全局变量和函数名称的混淆
	          renameGlobals: false,
	          // 通过固定和随机(在代码混淆时生成)的位置移动数组。这使得将删除的字符串的顺序与其原始位置相匹配变得更加困难。如果原始源代码不小,建议使用此选项,因为辅助函数可以引起注意。
	          rotateStringArray: true,
	          // 混淆后的代码,不能使用代码美化,同时需要配置 cpmpat:true;
	          selfDefending: true,
	          // 删除字符串文字并将它们放在一个特殊的数组中
	          stringArray: true,
	          rotateUnicodeArray: true,
	          //  stringArrayEncoding: 'base64',
	          stringArrayEncoding: ['base64'],
	          stringArrayThreshold: 0.75,
	          // 允许启用/禁用字符串转换为unicode转义序列。Unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。
	          unicodeEscapeSequence: false,
	          // 允许启用/禁用字符串转换为unicode转义序列。Unicode转义序列大大增加了代码大小,并且可以轻松地将字符串恢复为原始视图。建议仅对小型源代码启用此选项。
	          transformObjectKeys: true,
	        })
	      )
	    }
	},
}


chainWebpack

chainWebpack 是 Vue CLI 提供的一种更强大的方式来修改 Webpack 的配置。与 configureWebpack 不同,chainWebpack 使用 Webpack Chain API,它允许你以一种声明式的方式来修改 Webpack 配置

配置示例:

const path = require("path");
module.exports = {
  chainWebpack: (config) => {
    // 修改 HTML 插件的选项
    config.plugin('html').tap(args => {
      args[0].title = 'My App';
      return args;
    });

    // 修改模块规则
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
      .use('url-loader')
      .loader('url-loader')
      .options({
        limit: 10000,
        name: 'img/[name].[hash:7].[ext]'
      });

    // 去除 debugger
    config.when(process.env.NODE_ENV === 'production', config => {
      config.optimization.minimize(true);
      config.optimization.minimizer('terser').tap(args => {
        args[0].terserOptions.compress.drop_debugger = true;
        return args;
      });
    });

    // 添加别名
    config.resolve.alias
      .set('@components', resolve('src/components'))
      .set('@assets', resolve('src/assets'));

    // 添加额外的插件
    config.plugin('define').tap(args => {
      args[0]['process.env'].VUE_APP_VERSION = JSON.stringify(process.env.VUE_APP_VERSION || '');
      return args;
    });

    // 修改输出选项
    config.output.filename('[name].[contenthash].js');
  },
};

function resolve(dir) {
  return path.join(__dirname, dir);
}

参考链接: vue.config.js 配置configureWebpack 和 chainWebpack 以及一些常用配置

参考链接: [转载地址)

<think>好的,用户的问题是关于如何在vue.config.js配置renderer。我需要先理解用户的需求。用户可能在使用Vue.js时遇到了需要配置渲染器的情况,尤其是在使用运行时构建版本时,可能需要通过render函数来定义组件,而不是使用模板。因为根据引用[2],vue.runtime.xxx.js没有模板解析器,必须使用render函数。 接下来,我需要回忆Vue配置文件中如何设置renderer。通常,render函数是在Vue组件的选项中直接定义的,而不是在vue.config.js配置。但用户可能是指如何在整个项目中配置相关的Webpack设置,以支持render函数的使用,或者可能是预渲染(prerender)的配置,比如使用prerender-spa-plugin,这在引用[3]中提到过。 首先,检查引用内容。引用[2]提到vue.config.js用于配置,比如关闭生产提示,修改构建配置。引用[3]展示了configureWebpack的使用,添加了Workbox插件和预渲染。可能用户想了解如何配置预渲染,这涉及到生成静态页面的renderer。 用户的问题可能有歧义。如果是关于Vue组件中的render函数,那么不需要在vue.config.js配置,而是在组件中直接写。如果是预渲染,则需要安装prerender-spa-plugin并在vue.config.js中添加配置。 另外,可能用户混淆了render函数和渲染器的概念。Vue的运行时版本需要render函数来渲染组件,而vue.config.js中的配置更多是关于Webpack的调整,比如修改入口、插件等。所以需要明确用户的具体需求。 根据引用[3],预渲染的配置示例中使用了prerender-spa-plugin,这可能和renderer相关。所以,正确的步骤应该是安装该插件,然后在configureWebpack中添加对应的插件配置,指定路由和渲染选项。需要确保用户的环境变量正确,以及路由配置适合预渲染。 总结,用户可能需要的是如何通过vue.config.js配置预渲染,这涉及到使用prerender-spa-plugin,并设置需要预渲染的路由。同时,提醒用户注意运行时版本和完整版的区别,确保使用render函数而不是模板。</think>在 Vue.js 项目中,`vue.config.js` 中配置 `renderer` 通常与**预渲染(Prerendering)**或**服务端渲染(SSR)**相关。根据引用[3]提到的预渲染配置示例,以下是具体实现步骤: --- ### 1. **安装预渲染插件** ```bash npm install prerender-spa-plugin --save-dev ``` --- ### 2. **在 `vue.config.js` 中配置预渲染** ```javascript const PrerenderSPAPlugin = require('prerender-spa-plugin'); const path = require('path'); module.exports = { configureWebpack: (config) => { if (process.env.NODE_ENV === 'production') { config.plugins.push( new PrerenderSPAPlugin({ // 静态文件输出路径(需与打包路径一致) staticDir: path.join(__dirname, 'dist'), // 需要预渲染的路由列表 routes: ['/', '/about', '/contact'], // 渲染器配置(如无头浏览器设置) renderer: new PrerenderSPAPlugin.PuppeteerRenderer({ inject: {}, // 可注入全局变量 headless: true, // 是否启用无头模式 renderAfterDocumentEvent: 'app-mounted', // 等待事件触发后渲染 }) }) ); } } }; ``` --- ### 3. **关键配置说明** 1. **`routes`** 指定需要预渲染的路由路径,例如静态页面 `/about`。 2. **`renderer`** 使用 `PuppeteerRenderer` 作为渲染引擎,通过无头浏览器生成 HTML: - `headless: true` 表示不显示浏览器界面[^3]; - `renderAfterDocumentEvent` 表示等待 Vue 应用触发特定事件(如 `app-mounted`)后再渲染,确保数据加载完成[^3]。 --- ### 4. **注意事项** - **路由模式** 需使用 `history` 模式(而非 `hash` 模式),否则预渲染可能失效。 - **动态内容** 预渲染仅适用于静态内容,动态数据需结合接口预取或服务端渲染(SSR)[^3]。 - **兼容性** 若需兼容旧版浏览器,可通过 `renderer` 配置中的 `args` 添加 Chrome 启动参数,例如: ```javascript renderer: new PrerenderSPAPlugin.PuppeteerRenderer({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }) ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值