以webpack配置為例( 配置可自定義. 如: 開發(fā)環(huán)境一份, 生產(chǎn)環(huán)境一份, 如果需要, 再加一份測試版生產(chǎn)環(huán)境一份 )
方法一: 簡單快捷
let schema = 'http';
if (process.env.NODE_ENV === 'production') {
schema = 'https';
baseURL = `${schema}://192.168.13.*:10523`;
}
else {
baseURL = `${schema}://www.***.com`;
}
方法二:
copy-webpack-plugin 功能: 拷貝資源:
from 定義要拷貝的源目錄 from: __dirname + ‘/src/public’
to 定義要拷貝到的目標目錄 from: __dirname + ‘/dist’
toType file 或者 dir 可選朋其,默認是文件
force 強制覆蓋先前的插件 可選 默認false
context 可選 默認base context可用specific context
flatten 只拷貝文件不管文件夾 默認是false
ignore 忽略拷貝指定的文件 可以用模糊匹配
下面的代碼(用法)放置webpack的plugins [] 里面
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'), // 這里是拷貝后文件放置的目錄位置
to: config.build.assetsSubDirectory, //這里是需要拷貝的資源文件
ignore: ['.*']
}
])
generate-asset-webpack-plugin 功能: 生成文件至某個目錄下 :
tip: 當初用這個插件,是因為 , 需要在開發(fā)環(huán)境和測試環(huán)境還有生成環(huán)境下用到不同的api的 ip地址 ,
let config = {
testDev: {
apiUrl: "http:// xxx.xxxx.com"
}
}
var GenerateAssetPlugin = require('generate-asset-webpack-plugin');
function createServerConfig(compilation){
let cfgJson=config.testDev.apiUrl;
return JSON.stringify(cfgJson);
}
下面的代碼(用法)放置webpack的plugins [] 里面
new GenerateAssetPlugin({
filename: 'static/server.config.json',
fn:(compilation, cb)=>{
cb(null, createServerConfig(compilation))
}
})
/////////////////////////////////////////////////////////-------------------------------------------
貼上自己的項目webpack的簡單配置:
// config.js
module.exports = {
dev:{
apiUrl: "http://xxx.xxx.com"
},
build: {
apiUrl: "http://xxx.xxxxx.com"
}
}
// webpack.build.js
const path = require('path');
const config = require('./config')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin')唆铐;
function createServerConfig(compilation){
let cfgJson=config.build.apiUrl;
return JSON.stringify(cfgJson);
}
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: [
{
loader: 'babel-loader',
options: {
"presets": ["env", "react", "stage-2"]
}
}
],
exclude: /node_modules/
}, {
test: /\.css$/,
loader: "style-loader!css-loader"
}, {
test: /\.less$/,
loader: "style-loader!css-loader!less-loader"
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
title: 'manage',
filename: "index.html",
inject: 'body'
}),
new GenerateAssetPlugin({
filename: 'static/server.config.json',
fn: (compilation, cb) => {
cb(null, createServerConfig(compilation))
}
})
]
};