Bro*_*ski 23 javascript bundling-and-minification webpack
我们在单页面应用程序中使用WebPack.该应用程序部署到许多环境中.我们有一个要求,即应用程序需要在给定环境中调用特定端点.
为了给定环境提供端点地址,就是拥有一个环境模块.这是当前的解决方案(有很多,这不是问题的关键).但是,我们需要从缩小中排除config.js,以便在部署过程中将其覆盖.
config.js如下所示:
module.exports = {
env: {
endpointUrl: 'http://1.2.3.4',
authUrl: 'http://5.6.7.8'
}
};
Run Code Online (Sandbox Code Playgroud)
并使用以下内容引用:
const endpointUrl = config.env.endpointUrl;
const authUrl = config.env.authUrl;
Run Code Online (Sandbox Code Playgroud)
WebPack配置如下所示:
var webpack = require('webpack');
?
module.exports = {
entry: {
main: './src/js/main.jsx',
login: './src/js/login-main.jsx'
},
output: {
path: __dirname + '/dist',
filename: '[name].bundle.js'
},
devtool: 'source-map',
module: {
loaders: [{
test: /.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
plugins: ['transform-react-jsx'],
query: {stage: 0}
}, {
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}]
},
plugins: [
new webpack.ProvidePlugin({
fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch'
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEV || false))
})
]
};
Run Code Online (Sandbox Code Playgroud)
到目前为止,我们已经看过外部和模块加载器,但没有发现任何有效的东西.模块加载器中的排除仍会导致模块缩小.
我们研究过的一些SO问题:
dre*_*cat 18
Webpack 外部是避免捆绑某些依赖项的好选择.
但是,我们需要从缩小中排除config.js,以便在部署过程中将其覆盖.
将依赖项添加为外部不仅会将其从缩小中排除,而且甚至不会被webpack解决.
var webpack = require('webpack');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: './dist',
filename: 'bundle.js'
},
externals: {
'./config': 'config'
}
};
Run Code Online (Sandbox Code Playgroud)
添加外部用于需要您的路径config.js
.在我的简单示例中,路径对应于./config
.将它与将包含配置对象的全局变量相关联.在我的情况下,我只是用作config
变量名称(见下文config.js
).
const config = require('./config');
const endpointUrl = config.env.endpointUrl;
const authUrl = config.env.authUrl;
console.log(endpointUrl);
console.log(authUrl);
Run Code Online (Sandbox Code Playgroud)
由于您要阻止webpack解析config.js
模块,因此必须在运行时在环境中使用它.一种方法是将其作为config
全局上下文中的变量公开.
window.config = {
env: {
endpointUrl: 'http://1.2.3.4',
authUrl: 'http://5.6.7.8'
}
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以config.js
为任何给定环境加载特定文件.
<!DOCTYPE html>
<html>
<head>
<title>Webpack</title>
</head>
<body>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript" src="dist/bundle.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18815 次 |
最近记录: |