Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Webpack loaders in a Node app?

Is there a way to use Webpack loaders in a Node app / Run a Node app in a Webpack environment?

For instance I've got a webpack config that has a style-loader. In my Node app I do the following:

import style from 'style.css'

console.log(style.someClass)

I wanna run it like $ node app.js

like image 671
haxpanel Avatar asked Nov 08 '22 12:11

haxpanel


1 Answers

I've got an idea that might work, based on the Webpack NodeJS API. What if we put the code that we want to be able to use the Webpack environment (with the configured module loaders) into a module:

appModule.js:

import style from 'style.css'

console.log(style.someClass)

And require it with the following:

app.js:

import Webpack from 'webpack'
import MemoryFS from 'memory-fs'

...

webpackConfig.entry = 'appModule.js'
webpackConfig.output = 'appModule-out.js'

let compiler = Webpack(webpackConfig)
let mfs = new MemoryFS()

compiler.outputFileSystem = mfs
compiler.run(function (err, stats) {
    require(webpackConfig.output)
})

Probably it won't work because the require looks for the output on the physical FS... Can we require from the memory FS? I have not tried it yet - Any idea?

like image 96
haxpanel Avatar answered Nov 15 '22 05:11

haxpanel