Hi there,
I am getting crazy with webpack, because no configuration actually does exactly what I need. I thought that I had it, but now my <%= static_path(@conn, '/images/phoenix.png') %>
does not work within sass and I don’t see any way to fix that, so the only option I see is to get some help.
Here is my webpack.config.js:
const path = require('path');
module.exports = function (env, argv) {
return {
devtool: env.production ? 'source-maps' : 'eval',
entry: {
app: './js/app.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.scss$/,
use: env.production ? [
{
loader: 'file-loader',
options: {
name: '[name].css',
outputPath: '../css',
publicPath: 'http://localhost:8080/'
}
},
{
loader: "sass-loader", options: {sourceMap: env.development} // compiles Sass to CSS
}
] : [
"style-loader",
"css-loader",
"sass-loader",
]
}
],
},
resolve: {
modules: ['node_modules', path.resolve(__dirname, 'js')],
extensions: ['.js'],
},
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
},
},
output: env.production ? {
path: path.resolve(__dirname, '../priv/static/js'),
filename: '[name].js',
publicPath: '/',
} : {
path: path.resolve(__dirname, 'public'),
filename: '[name].js',
publicPath: 'http://localhost:8080/',
},
};
};
And the relevant parts of my package.json:
"scripts": {
"deploy": "webpack --mode production --env.production",
"build": "webpack --mode production --env.production",
"start": "yarn run watch",
"watch": "webpack-dev-server --mode development --env development --hot --watch-stdin"
},
assets/js.app.js
has the line require("../css/app.scss")
inside, which does work well.
Within templates/layout/app.html.eex, I did the following to get the js in:
<%= if (Mix.env == :dev) do %>
<script src='http://localhost:8080/app.js'></script>
<% else %>
<script src="<%= static_path(@conn, "/js/app.js") %>"></script>
<% end %>
(And something similar without the else clause for the production app.css file)
I understand that with the webpack-dev-server, phoenix does not handle the files and can therefore not extrapolate <%= static_path(@conn, '/images/phoenix.png') %>
from my .sass files.
Now how can I add sass support to phoenix / webpack with automatic reloading and static_path working? Please give me some hint. I checked: https://github.com/phoenixframework/phoenix, but they don’t seem to tackle that problem at all with their webpack setup.