Skip to content

Instantly share code, notes, and snippets.

@oxycoder
Created June 24, 2024 02:47
Show Gist options
  • Save oxycoder/5906ceeb0c38d2fbf03abab8a321102a to your computer and use it in GitHub Desktop.
Save oxycoder/5906ceeb0c38d2fbf03abab8a321102a to your computer and use it in GitHub Desktop.
Angular custom webpack to generate external assets URL
...
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
}
}
}
...
const webpack = require('webpack');
module.exports = {
module: {
rules: [
{
test: /\.scss$|\.sass$/,
use: [
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: ['src/scss'],
},
additionalData: async (content, loaderContext) => {
let cdnUrl = '';
if (process.env.ANGULAR_ENV === 'local') {
cdnUrl = 'https://cdn.example.com'; // TODO: Replace with public CDN URL
}
// Prepend the cdnUrl variable declaration to the content
return `$cdn-url: "${cdnUrl}";\n${content}`;
},
},
},
],
},
],
},
};
@function get-asset($local-path) {
@if not variable-exists(cdn-url) {
@return url('#{$local-path}');
} @else {
// remove ~ from local-path if exist
$local-path: $cdn-url + str-replace($local-path, '~', '');
@return url('#{$local-path}');
}
}
.image-search {
background-image: get-asset('~assets/image/search.svg');
}
"scripts": {
"ng": "ng",
"start": "ANGULAR_ENV=local ng serve",
...
},
"devDependencies": {
...
"@angular-builders/custom-webpack": "^14.1.0",
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment