webpack打包时如何抽离出项目配置文件单独打包

在构建项目的时候 想单独打包配置文件,生产上可以自行改变配置文件
项目结构是这样的

|_node_modules/
|_src/
   |_components/
   |_containers/
   |_reducers/
   |_actions
   |_utils/
   |_index.js
   |_config.js

其中 index.js是项目入口,config.js是项目的配置文件

打包的时候 想将config.js单独抽离出来 打包成一个单独的文件
方便生产环境定制参数
我应该如何做

附上我的webpack.config.js

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        app: './src/index.js',
        vendor: ['react', 'react-dom', 'react-router','react-redux','./src/service']
    },
    output: {
        path: __dirname + '/build/',
        publicPath: './',
        filename: 'js/bundle.js',
        chunkFilename: 'js/[chunkhash].js'
    },
    module: {
        rules: [
            {
                test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'assets/[hash].[ext]'
                    }
                }]
            },
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            }
        ]
    },
    // devServer: {
    //     host: '0.0.0.0',
    //     hot: true,
    //     clientLogLevel: 'info',
    //     historyApiFallback: true,
    //     contentBase: './build/'
    // },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            filename: 'js/vendor.js'
        }),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './index.html',
            hash: true
        }),
        // new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        })
    ]
};
阅读 8.2k
3 个回答

我自己的解决方案分享下:
在html中单独引入一个global.js

// global.js 
window.g= {
    url:'www.a.com',
    path:'path/to/target/'
}

然后在项目中再写一个配置文件 这个配置文件webpack打包引用 这样写

// config.js
const G =  window.g;
export const url =  G.url || 'www.baidu.com';
export const path =  G.path || '/';

项目中需要用配置的地方直接引入 config.js

// biz.js

import {url} from '../config';
console.log(url)

使用的时候在页面开头引入global.js,再引入打包文件,这样可以比较完美的做到解耦配置文件

<script src="global.js"></script>
<script src="bundle.js"></script>

顶起来,刚接触webpack,看看有没有好的解决方法。

我也遇到过这种问题。

考虑到一些配置,能让任何人修改,而不需要进行编译。

我直接把配置文件挂到window上了,其他需要用配置的js文件默认读取window上的字段而已。

因为我想着如果用webpack打包,config就变成模块了,这样就必须进行打包后才能生效,所以目前还没想到好方法。

也想听听各位老师方案。