简体   繁体   中英

Dynamic require in webpack not working

Could not resolve dynamic require using webpack. Getting error

WARNING in ./ace/config.js
112:21-40 Critical dependency: the request of a dependency is an expression

WARNING in ./ace/config.js
142:39-46 Critical dependency: require function is used in a way in which
dependencies cannot be statically extracted        

WARNING in ./ace/config.js
124:12-131:14 Critical dependency: the request of a dependency is an
expression 

There are 5 files that use static require, only 1 file with dynamic require.

My webpack config file is something like this

var webpack = require('webpack');

module.exports = {
 context: __dirname + '/app',
 entry: {
    services: ["./init.js"]
},
output: {
    path: __dirname + '/public/javascript',
    filename: "[name].bundle.js?v=[hash]"
},
module: {
    loaders: [
        { test: /\.json$/, loader: 'json-loader' },
        {
            loader: 'babel-loader',
            query: {
                presets: ['es2015', 'stage-0']
            }
        },
        { test: /\.css$/, loader: "css-loader" }
    ]
},
node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
},
target: 'node'
};

We need to resolve those dynamic requires using webpack functionality [ https://webpack.github.io/docs/context.html][1]

Just need to mention the directory from where webpack can resolve those dependencies.You can also explore ContextReplacementPlugin of webpack for the same.

   this =>  require([module])
   to => require(['./directory/' + module + '.js'])

where module name is dynamic

Solved by replacing commented lines by the next ones where directory is selected as node_modules .

// var dns = require('dns');
var directory = './node_modules/';
var dns = require([directory + 'dns' + '.js']);
// var request = require('request');
var request = require([directory + 'request' + '.js']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM