如何在webpack配置中运行动态代码

How to run dynamic code in webpack config

本文关键字:运行 动态 代码 配置 webpack      更新时间:2023-09-26

我有多个angular指令/过滤器/服务,我想在webpack中重用它们。一般来说,我想为这些文件创建一个angular模块。(总是根据某些用户输入而不同,但这不是此票据的问题)

我使用webpack从我的JS文件,而不是从webpack。配置为:

webpack({
        entry: {
        firstFile: path.resolve(__dirname,'../path/to/firstFile.js'),
        secondFile: path.resolve(__dirname,'..//path/to/secondFile.js')
},
    output: {
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: 'Path to file to babel',
            }
        ]
    }
}, function(err, stats) {
});

所以在这个特定的例子中,我从firstFile.jssecondFile.js构建bundle.js

这个创建bundle没问题,但是我漏掉了一些用来创建angular.module的代码。

应该包含如下内容:

const ngModuleName = 'myModuleName'
export default ngModuleName
const ngModule = angular.module(ngModuleName, [])
ngModule.directive('firstFile', firstFile)
ngModule.filter('secondFile', secondFile)

或者像处理静态文件一样,直接执行这类代码,不需要任何其他条目:

import firstFile from '../path/to/firstFile.js'
import secondFilefrom '../path/to/secondFile.js'
const ngModuleName = 'myModuleName'
export default ngModuleName
const ngModule = angular.module(ngModuleName, [])
ngModule.directive('firstFile', firstFile)
ngModule.filter('secondFile', secondFile)

是否有一种方法在条目内部执行?或者其他方式如何动态地将源代码添加到webpack进程中?

谢谢你的建议

我发现可以通过webpack加载器做我想做的事情。

基本上我写我自己的加载器,我使用它在webpack.config像:

{
    test: bin_dir,
    loader: path.resolve(__dirname, 
        "./my-loader.js?"+JSON.stringify(myLoaderSettings))
},

然后在我的加载器中,我可以很容易地操作输入文件的源。在我的例子中,我在条目中添加了新的空白文件,并在源中添加了我需要的任何内容。

module.exports = function myLoader(source) {
    // Source code of existing entry
    console.log(source);
    // Query, in my case it's result of JSON.stringify(myLoaderSettings)
    console.log(this.query);
}