如何阻止webpack

时间:2017-04-12 11:34:24

标签: javascript node.js configuration webpack external

您好我正在使用webpack将我的项目文件捆绑到一个文件中。但是,我不希望webpack捆绑我的config.js文件,其中所有配置都已设置。我想这在输出文件夹中保持独立,但不确定是否实现此目的。

我当前的设置是

//index.js file
#!/usr/bin/env node
'use strict';
let config = require('config.js);
let read = require('read.js);
console.log('i am running through command line');

//read.js file
'use strict'
console.log('read a text file');

//config.js 
'use strict';
module.exports = {
name: 'test'
}

//webpack.config.js
let webpack = require('webpack');
let path = require('path');
let fs = require('fs');

let nodeModules = {};
fs.readdirSync('node_modules')
.filter(function (x) {
    return [ '.bin' ].indexOf(x) === -1;
})
.forEach(function (mod) {
    nodeModules[mod] = 'commonjs ' + mod;
});

module.exports = {
entry: [ 'babel-polyfill', './index.js' ],
target: 'node',
node: {
    __dirname: true
},
output: {
    path: path.join(__dirname, 'webpack_bundle'),
    filename: '[name].js',
    libraryTarget: 'commonjs'
},
module: {
    loaders: [
        {
            test: /\.js$/,
            loader: 'shebang-loader'
        },
        {
            test: /\.js$/,
            loader: 'babel-loader',
            query: {
                presets: [ 'es2015' ]
            }
        } ]
},
resolve: {
    extensions: [ '.js' ]
},
plugins: [
    new webpack.BannerPlugin({banner: '#!/usr/bin/env node', raw: true 
})
]
,
    externals: nodeModules
};

注意:为了简洁起见,我已经大大简化了代码示例

目前,当我运行webpack命令时,我得到一个包含webpack_bundle文件的文件夹index.js - index.js文件包含依赖项config.js和{{1 }}。但是,我希望将read.js依赖项捆绑到read.js文件中,但index.js依赖项保留在一个单独的文件中,这是捆绑的webpack输出所需要的。因此,运行config.js命令后,文件夹webpack_bundle应包含两个文件 - webpackindex.js。我已经尝试通过将以下键值添加到外部对象config.js来修改外部,但这不起作用。我还通过将config.js指定为入口点来创建了一个额外的入口点,但这也没有用。我无法解决这个问题,而webpack文档对于如何实现这一目标并不清楚。请帮忙!

1 个答案:

答案 0 :(得分:6)

如果您希望自己的配置位于单独的捆绑包中,则可以使用 config.js 动态导入require.ensure文件,从而创建分割点

require.ensure([], function() {
  let config = require('./config.js');
});

您的配置将在另一个捆绑包中。

修改

如果您不希望自己的配置文件被Webpack捆绑,我认为您可以使用 IgnorePlugin

module.exports = {
  //...
  plugins: [new webpack.IgnorePlugin(/^\.\/config\.js$/)]
}

使用 copy-webpack-plugin 复制您的config.js文件。