javascript - 我如何防止 .js 文件被 webpack 捆绑

标签 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.jsread.js。但是,我想要的是将 read.js 依赖项捆绑到 index.js 文件中,但将 config.js 依赖项捆绑到保留在一个单独的文件中,这是捆绑的 webpack 输出所需要的。因此,在运行 webpack 命令后,文件夹 webpack_bundle 应该包含两个文件 - index.jsconfig.js。我已经尝试通过将以下键值添加到外部对象 config: './config.js' 来修改外部,但这没有用。我还通过将 config.js 指定为入口点来创建一个额外的入口点,但这也不起作用。我无法弄清楚这一点,webpack 文档也不清楚如何实现这一点。请帮忙!

最佳答案

如果您希望您的配置在一个单独的包中,您可以创建一个拆分点,通过使用require 动态导入您的config.js 文件.确保:

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

您的配置将在一个单独的包中。

编辑:

如果你不想让你的配置文件被Webpack打包,我想你可以使用IgnorePlugin:

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

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

关于javascript - 我如何防止 .js 文件被 webpack 捆绑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43368399/

相关文章:

javascript - Vue项目中DOM元素变成Null

javascript - TypeError : user. 保存不是函数 [mongoose]

javascript - nwjs (node-webkit) 修改网站 javascript 和 css

asp.net - 以编程方式设置自定义404错误页面

java - 获取 Eclipse 运行时配置键和值

.net - .NET 中用于通过 XML/Yaml/INI 配置的 Lua?

javascript - 使用 JQuery/Javascript 进行动态 HTML 值计算

Javascript:类似于带有属性名称的 string.format

javascript - 在 GCP App Engine 上部署 NodeJS Express 应用程序时出现服务器错误 500

node.js - npm 在哪里寻找 package.json 文件?