haxpanel
haxpanel

Reputation: 4678

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

Upvotes: 5

Views: 1129

Answers (3)

haxpanel
haxpanel

Reputation: 4678

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?

Upvotes: 2

Filip Dupanović
Filip Dupanović

Reputation: 33640

You should be able to create a compilation targeting the node environment which you can ultimately run by simply calling node output.js and this will immediately execute the entry point module.

Be aware, in case that you're using a newer version of Node.js, that Webpack doesn't support the ES2015 module syntax, so you'll have to configure Babel for Node.js as well to transform the modules.

Upvotes: 0

simbolo
simbolo

Reputation: 7494

Webpack loaders aren't transpilers or interpreters, they simple gather assets that are then handled off to something like SASS or a text concatenator; within the confines of Webpacks environment.

Thus it is not possible to reuse them in the way you want, because while you can of course import and call them (they're still just functions + classes), they don't convert CSS to JSON objects (they don't do this) as you have written in your desired example.

It looks like you just need a JS implementation of a css parser - have a look at https://github.com/reworkcss/css

Upvotes: 0

Related Questions