@xysfe/multi-origin-webpack-plugin
v1.0.4
Published
A webpack plugin for inject variable to support multi origin
Downloads
30
Maintainers
Readme
MultiOriginWebpackPlugin
提示
- 此插件依赖于
html-webpack-plugin
插件 - 该插件会强制更改项目中的publicPath配置
- css样式中使用了相对路径的url,如
../img/xxx.png
,若构建后引用的资源路径不正确,需要将使用了「ExtractTextPlugin」或「MiniCssExtractPlugin」loader的publicPath重设为'../'
,可参考该文档MiniCssExtractPlugin
下载
npm i @xysfe/multi-origin-webpack-plugin
使用方式
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MultiOriginWebpackPlugin = require('@xysfe/multi-origin-webpack-plugin').web
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin(),
new MultiOriginWebpackPlugin()
]
}
vue.config.js
const MultiOriginWebpackPlugin = require('@xysfe/multi-origin-webpack-plugin')
module.exports = {
chainWebpack: config => {
config
.plugin('multi-origin')
.use(new MultiOriginWebpackPlugin())
}
}
注意事项
插件强依赖于NODE_ENV环境变量,用于处理线上发布后会导致测试环境资源不可访问的现状,若没有该变量则会退出构建。
正式环境的NODE_ENV必须是production,否则无法构建出正确的资源路径。
NODE_ENV环境变量注入方式:
// file: package.json
// webpack
{
"scripts": {
"dev": "cross-env NODE_ENV=development webpack...",
"dist": "cross-env NODE_ENV=production webpack..."
}
}
// vuecli
// vuecli默认的mode为production
{
"scripts": {
"dev": "vue-cli-service build --mode development",
"dist": "vue-cli-service build"
}
}
功能
- 插件将会注入全局变量,来获取到PHP返回的CDN地址,并且拼接成一个带协议和域名的链接,生成的页面片如下
<!DOCTYPE html>
<html>
<head>
<script>var __global_cdn__=(function(b,a){if(a.indexOf('http')===0){return a}else{if(a.indexOf('//')===0){return b.protocol+a}else{return b.protocol+'//'+b.host+a}}})(location, '{$CDN}')</script>
<meta charset="utf-8">
<title>Webpack App</title>
</head>
</html>
- 插件会检测代码中是否有指定的代码片段,在编译过程中提出警告,效果如下
- 插件会在js中注入动态public path,用于实现多域名cdn分离的效果,注入后的代码如下
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/static/insuranceV2/";
/******/
/******/ // set dynamic webpack public path by multi-origin-webpack-plugin
/******/ __webpack_require__.p = window.__global_cdn__ ? window.__global_cdn__ + '/insuranceV2/' : '/static/insuranceV2/';
/******/
配置项
| Name | Type | Default | Description | | ---- | ---- | ---- | ---- | | regex | {Array} | ['xiaoyusan.com'] | 检测代码中需要匹配的字符串 | | shouldCheck | {Boolean} | true | 选择是否需要提示域名警告 | | fixedPublicPath | {Boolean} | false | 选择是否保持原来的publicPath配置(ssr开发环境使用) |