Search code examples
javascriptwebpackwebpack-loader

How to access DOM from webpack loader


I'm writing a webpack loader for a specific file extension, and I would like to append a custom import to the DOM

module.exports = function(source) {
    ...
    document.appendChild(myImport)

    return `export default 'hello'`;
}

but the DOM is not accessible

ReferenceError: document is not defined

Is there a way to access the DOM from my loader?

My webpack configuration is:

const path = require('path')

module.exports = {
    ...
    module: {
        rules: [{
            test: /\.myextension$/,
            use: {
                loader: 'my-loader'
            }
        }]
    }
};

Solution

  • No, the code from loader is going to be ran on a node.js env, which has no power over the dom (browser env). To be able to manipulate the dom, you would have to output a code though loader which would be inserted on that type of file and then when executed on the browser it would do the modifications.

    Something like:

    module.exports = function(source) {
        return `export default function(){
            document.appendChild(myImport)
        }`;
    }