简体   繁体   中英

Webpack - dynamic require and paths

My webpack.config file looks like this

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: {
        app: './app'
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name]-bundle.js'
    }
};

I have some dynamic requires that look like this

function loadModule(modName, cb, onErr){
    if (modName == 'contacts') require(['../modules/contacts/contacts', 'html!../modules/contacts/contacts.htm'], cb);
    else if (modName == 'tasks') require(['../modules/tasks/tasks', 'html!../modules/tasks/tasks.htm'], cb);
    else onErr();
}

Which work great. I'm seeing 1.1-bundle.js and 2.2-bundle.js getting added to my build folder .

The problem is, when these dynamic requires are triggered, I'm seeing 404s in my network tab, since webpack is trying to load 1-1.bundle.js from the root of my project, instead of the build folder where I told webpack to put it.

How do I correct this?

You probably need to set the public path - basically, you tell webpack where on your webserver it will find the built files, which for you seems to the the build folder.

{
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name]-bundle.js',
        publicPath: '/build/',
    },
}

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