If you worked with webpack, you know how confusing it's configuration can become. Because of this, many frameworks & code generators abstract it away from the application developer. It works nice in simple case - like demo apps, but can become painful in when we want to customize the set up. Not only we have to know webpack & it's loaders, but on top of that we need to the quirky way of changing the config, without breaking the framework.
Application
The example application we have here, was created following the npm example for getting started doc
$ npm init nuxt-app webpack-nuxt
The code created by this command you can find here:
https://github.com/marcin-wosinek/webpack-nuxt/tree/eb44c5a85eaf421b50bfe53b9e07b7e27e4ec34c
As of now, we are limited to webpack in version 4 - it's previous version. And based on this discussion you shouldn't expect update to webpack 5 before major release of nuxt.
Adding loaders
As you can see on extend webpack config, the correct place to tweak webpack config is nuxt.config.js
. Let's say we want to load .weird
files as just a string. In webpack it's achieved with raw-loader
.
You should add inside export default {
of nuxt.config.js
following code:
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
extend(config) {
config.module.rules.push({
test: /\.weird$/,
loader: "raw-loader"
});
}
}
Note! We are push
ing new object to config.module.rules
. If we were overriding the whole array, we would drop all the rules defined by the framework, therefore break our build.
Most likely this will fail, so you should install the raw-loader:
$ npm install --save-dev raw-loader
With all that in place, you should be able to have pages/index.vue
:
<template>
<div>
{{ info }}
</div>
</template>
<script>
import info from "./raw.weird";
export default {
async asyncData() {
return { info };
}
};
</script>
loading content from a raw.weird
file next to it.
Links
Summary
In this article, we have seen how to customize which loader is used for a given file extension in nuxt. If you want to see the whole code base, you can find it here:
https://github.com/marcin-wosinek/webpack-nuxt