Created
June 24, 2024 02:47
-
-
Save oxycoder/5906ceeb0c38d2fbf03abab8a321102a to your computer and use it in GitHub Desktop.
Angular custom webpack to generate external assets URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
"architect": { | |
"build": { | |
"builder": "@angular-builders/custom-webpack:browser", | |
"options": { | |
"customWebpackConfig": { | |
"path": "./extra-webpack.config.js" | |
}, | |
} | |
} | |
} | |
... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`; | |
}, | |
}, | |
}, | |
], | |
}, | |
], | |
}, | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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}'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.image-search { | |
background-image: get-asset('~assets/image/search.svg'); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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