Yeoman incorrect vendor image paths when building app (jquery-ui + angular generator) - yeoman

I am using generator-angular 0.15.1 and I added jquery-ui. To add the jquery-ui css I had to add the following to the bower.json in the 'overrides' section:
"jquery-ui": {
"main": [
"themes/base/jquery-ui.css",
"jquery-ui.js"
]
}
Now when building with grunt I don't get the images from /bower_components/jquery-ui/themes/*/images folder in the /dist/styles/images folder so I tried in Gruntfile.js (from another question):
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
},
<<<<<<<< ADDED
{
expand : true,
flatten : true,
cwd : '/bower_components/jquery-ui/themes/*/images',
src : '**/*.{png,jpg,jpeg,gif}',
dest : '<%= yeoman.dist %>/styles/images'
}
>>>>>>>>
]
}
}
But with no success.
Here is my Gruntfile.js:
// generator-angular 0.15.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required Grunt tasks
require('jit-grunt')(grunt, {
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn'
});
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all', 'newer:jscs:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'newer:jscs:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'postcss']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Make sure code styles are up to par
jscs: {
options: {
config: '.jscsrc',
verbose: true
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
postcss: {
options: {
processors: [
require('autoprefixer-core')({browsers: ['last 1 version']})
]
},
server: {
options: {
map: true
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
js: ['<%= yeoman.dist %>/scripts/{,*/}*.js'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
],
patterns: {
js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
}
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
ngtemplates: {
dist: {
options: {
module: 'angularFinancialPortalApp',
htmlmin: '<%= htmlmin.dist.options %>',
usemin: 'scripts/scripts.js'
},
cwd: '<%= yeoman.app %>',
src: 'views/{,*/}*.html',
dest: '.tmp/templateCache.js'
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'*.html',
'images/{,*/}*.{webp}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'postcss:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'postcss',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'postcss',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'newer:jscs',
'test',
'build'
]);
};

I finally got it to work. My main fault was in the path, here is what I added:
imagemin: {
dist: {
files: [
{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
},
<<<<<<<<<<<<<<<<<< ADDED
{
expand : true,
cwd : 'bower_components/jquery-ui/themes/base/images',
src : '**/*.{png,jpg,jpeg,gif}',
dest : '<%= yeoman.dist %>/styles/images'
}
>>>>>>>>>>>>>>>>>>>
]
}
}
Note that the flatten flag is not mandatory.
For completion I also rewrite these image files (as it was set for the regular images) for browser catching purposes:
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
<<<<<<<< ADDED
'<%= yeoman.dist %>/styles/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
>>>>>>>>
'<%= yeoman.dist %>/styles/fonts/*'
]
}
}

Related

How to you modify the precache manifest file generated by Workbox? Need urls to have preceding '/'

In the generated precache-manifest.*.js file the URLs all reference relative paths when I need absolute since my app will have some sub-directories as well.
Example of generated file:
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "1d94d834b7044ec6d4e9",
"url": "js/app.js"
},
{
"revision": "632f09e6ed606bbed1f1",
"url": "css/app.css"
},
...
}
When I need it to look like this:
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "1d94d834b7044ec6d4e9",
"url": "/js/app.js"
},
{
"revision": "632f09e6ed606bbed1f1",
"url": "/css/app.css"
},
...
}
I'm using webpack 4.41.0 and workbox-webpack-plugin 4.3.1
Any help would be greatly appreciated! I can add more detail if needed as well.
Here's my webpack config:
let config = {
entry,
stats: {
hash: false,
version: false,
timings: false,
children: false,
errorDetails: false,
entrypoints: false,
performance: inProduction,
chunks: false,
modules: false,
reasons: false,
source: false,
publicPath: false,
builtAt: false
},
performance: { hints: false },
// Valid options: "production" | "development" | "none"
mode: inProduction ? 'production' : 'development',
plugins: [
new CopyPlugin(copyConfig),
new webpack.ProvidePlugin(providers), // Providers, e.g. jQuery
new WebpackNotifierPlugin({ title: 'Webpack' }), // OS notification
new VueLoaderPlugin(), // Vue-loader
new CleanWebpackPlugin(pathsToClean, cleanOptions), // Clean up pre-compile time
new ManifestPlugin(manifestOptions), // Manifest file
new FriendlyErrorsWebpackPlugin({ clearConsole: true }), // Prettify console
new MiniCssExtractPlugin(cssOptions), // Extract CSS files
new WebpackMd5Hash(), // use md5 for hashing
{
/* Laravel Spark RTL support */
apply: (compiler) => {
compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
exec('node_modules/rtlcss/bin/rtlcss.js public/css/app-rtl.css ./public/css/app-rtl.css', (err, stdout, stderr) => {
if (stdout) process.stdout.write(stdout);
if (stderr) process.stderr.write(stderr);
});
});
}
}
],
module: {
rules: [
{
test: /\.vue$/,
use: ['vue-loader']
},
{
test: /\.s?css$/,
use: [
'style-loader',
{
loader: MiniCssExtractPlugin.loader,
options: { hmr: isHot } // set HMR if flagged
},
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.json', '.vue'],
modules: ['node_modules'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'~': path.join(__dirname, 'resources/assets/js'),
jquery: "jquery/src/jquery",
}
},
output: {
filename: 'js/[name].js',
// chunkFilename: inProduction ? 'js/[name].[chunkhash].js' : 'js/[name].js',
path: publicPath,
},
optimization: {
...optimization,
concatenateModules: false,
providedExports: false,
usedExports: false,
},
devtool: inDevelopment ? 'eval-source-map' : false,
devServer: {
headers: {
'Access-Control-Allow-Origin': '*'
},
port: port,
contentBase: publicPath,
historyApiFallback: true,
noInfo: false,
compress: true,
quiet: true,
hot: isHot,
}
}
And my GenerateSW:
new GenerateSW({
// The cache ID
cacheId: 'pwa',
// The path and filename of the service worker file that will be created by the build process, relative to the webpack output directory.
swDest: path.join(publicPath, 'sw.js'),
clientsClaim: true,
skipWaiting: true,
// Files to exclude from the precache
exclude: [/\.(?:png|jpg|jpeg|svg)$/, /\.map$/, /manifest\.json$/, /service-worker\.js$/, /sw\.js$/],
// Default fall-back url
navigateFallback: '/',
// An optional array of regular expressions that restricts which URLs the configured navigateFallback behavior applies to.
// This is useful if only a subset of your site's URLs should be treated as being part of a Single Page App.
navigateFallbackWhitelist: [
/^\/media\//,
/^\/settings\//,
],
// Runtime cache
runtimeCaching: [
{
urlPattern: new RegExp(`${process.env.APP_URL}`),
handler: 'NetworkFirst',
options: {
cacheName: `${process.env.APP_NAME}-${process.env.APP_ENV}`
}
},
{
urlPattern: new RegExp('https://fonts.(googleapis|gstatic).com'),
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts'
}
}
]
}
)
And a couple of defined common variables:
...
// Production flag
const inProduction = process.env.NODE_ENV === 'production'
const inDevelopment = process.env.NODE_ENV === 'development'
// HMR
const isHot = process.argv.includes('--hot')
// Public/webroot path
const publicPath = path.resolve(__dirname, 'public')
// Primary webpack entry point(s)
const entry = {
/*
* JS entry point/Vue base component
* Make sure to import your css files here, e.g. `import '../sass/app.scss'`
*/
app: path.resolve(__dirname, 'resources/assets/js/app.js'),
}
...
For anyone visiting this question, you can use the webpack output.publicPath setting to add a prefix to your manifest URLS like so:
plugins: [
new InjectManifest({}) // Left here just for reference
],
output: {
publicPath: '/' // You can add your prefix here
}

webpack: Inline css for a splash screen (above the fold css)

Im trying to figure out why a css segment will not run through 'style-ext-html-webpack-plugin'.
Currently I have a .CSS file with rules for the splash screen.
It's being extracted using 'extract-text-webpack-plugin' and injected to the template's <head> with 'extract-text-webpack-plugin'.
problem is, the file never gets run through 'style-ext-html-webpack-plugin' and I can't wrap my head around how to debug it.
(Ideally, I'd like to have a .SCSS file so it can be themeable through a .env file. i.e: have splash.scss exclusively extracted and inlined in the <head> after being injected with some theme colors)
webpack.config.js:
....
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //used for above-the-fold css (such as splash-screen)
const StyleExtHtmlPlugin = require('style-ext-html-webpack-plugin');
const extractSplashCSS = new ExtractTextPlugin('splash.css');
module.exports = {
entry: {...},
output: {...},
resolve: {...},
plugins: [
...,
new HtmlWebpackPlugin({
title: enviroments.TITLE,
splashScreenTitle: enviroments.SPLASH_SCREEN_TITLE,
template: 'src/index.html',
cache: true,
favicon: enviroments.FAVICON || './src/assets/images/favicon.ico',
inject: 'body'
}),
extractSplashCSS,
new StyleExtHtmlPlugin('splash.css')
],
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{
test: /\.css$/,
loader: 'style-loader!css-loader!resolve-url-loader?import=false',
exclude: [path.join(path.resolve('./src'), 'common/app/splash.css')]
},
{
test: /\.css$/,
loader: extractSplashCSS.extract({
use: 'css-loader'
}),
include: [path.join(path.resolve('./src'), 'common/app/splash.css')]
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader?importLoaders=1',
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')];
}
}
},
'resolve-url-loader?sourceMap',
{
loader: 'sass-loader?sourceMap',
options: {
includePaths: path.resolve('./src'),
data: `
$color-primary: ${theme.PRIMARY};
....
`
}
}
]
},
....
]
}
};
index.js:
...
// above the fold css
import 'common/app/splash.css';
Needed to update html-webpack-plugin to 2.29.0.
I've managed to solve this issue, using a sass file that can be themeable with variables from .env file:
I had to explicitly exclude the splash file from the normal sass flow and create another loader definition explicitly for it:
...
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //used for above-the-fold css (such as splash-screen)
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
module.exports = {
...
plugins: [
...
new HtmlWebpackPlugin({
...
}),
new ExtractTextPlugin('splash.css'),
new StyleExtHtmlWebpackPlugin('splash.css'),
],
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.css$/, loader: 'style-loader!css-loader!resolve-url-loader?import=false' },
{
test: /\.scss$/,
exclude: [path.join(path.resolve('./src'), 'common/app/splash.scss')],
use: [
.....
]
},
{
test: /\.scss$/,
include: [path.join(path.resolve('./src'), 'common/app/splash.scss')],
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {minimize: true}
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')];
}
}
},
{
loader: 'sass-loader',
options: { data: `$color-primary: ${theme.PRIMARY};` }
}
]
})
},
]
}
};

PostCSS CSSNext #media and color() not working with webpack 2

I'm upgrading a project from webpack 1 to 2, and am seeing some strange behavior with postcss-cssnext where some css next features, most notably color() functions and all my #media queries just aren't working anymore.
My webpack config with webpack 2 looks like this. What am I doing wrong here?
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
localIndentName: 'localIdentName=[name]__[local]___[hash:base64:5]',
sourceMap: true,
modules: true,
importLoaders: 1
}
},
{
loader: 'postcss-loader',
options: {
plugins: [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
]
}
}
]
}
postcss-loader is probably responsible for this change (1.3.x).
According to doc, you should use a function for "plugins" option.
Or use an array but in a postcss.config.js file.
module.exports = {
module: {
rules: [
{
test: /\.css/,
use: [
…
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
];
}
}
}
]
}
]
}
}
Or via postcss.config.js
module.exports = {
plugins: [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
]
}
(and in webpack)
module.exports = {
module: {
rules: [
{
test: /\.css/,
use: [
…
'postcss-loader',
]
}
]
}
}

How to load image by using webpack in .Net MVC

Currently using web pack in .net MVC with Angular 2 development. Hope someone can identify and explain what I have done wrong in the config.
Problem.
Unable to load images (404), check in browser and only 2 images being loaded.
In my project images folder,
webpack.config.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;
// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
resolve: { extensions: [ '', '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /\.html$/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
};
// Configuration for client-side bundle suitable for running in browsers
var clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot-client.ts' },
output: { path: path.join(__dirname, './wwwroot/dist') },
devtool: isDevBuild ? 'inline-source-map' : null,
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
entry: { 'main-server': './ClientApp/boot-server.ts' },
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map',
externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});
module.exports = [clientBundleConfig, serverBundleConfig];
webpack.config.vendor.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');
module.exports = {
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [
{ test: /\.(png|jpg|ico|gif|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader' },
{ test: /\.css$/, loader: extractCSS.extract("style-loader", "css-loader") }
]
},
entry: {
vendor: [
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/platform-server',
'angular2-universal',
'angular2-universal-polyfills',
'animate.css/animate.min.css',
'bootstrap',
'bootstrap/dist/css/bootstrap.min.css',
'bootstrap/dist/js/bootstrap.min.js',
'es6-shim',
'es6-promise',
'font-awesome/css/font-awesome.min.css',
'html5shiv',
'isotope-layout',
'jquery',
'wowjs/dist/wow.min.js',
'zone.js',
'./js/main.js',
'./js/respond.min.js',
'./css/main.css',
'./css/prettyPhoto.css',
'./css/responsive.css'
],
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
publicPath: '/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
, new CopyWebpackPlugin([{ from: 'images', to: './images' }])
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
])
};
_Layout.cshtml

Copy files from parent folder with grunt-contrib-copy

I am trying to copy files over from a parent folder using grunt-contrib-copy. My folder structure is:
-libs
-html5shiv
-respond
-jquery
-apps
-exampleApp1
-GruntFile.js
-build
-exampleApp2
-GruntFile.js
-build
I am trying to copy all the JavaScript files from the libs folder over to the apps/exampleApp1/build when I run the GruntFile.js in exampleApp1. I have the following setup in the GruntFile.js:
build_dir: 'build';
lib_files: {
js: [
'../../libs/html5shiv/dist/html5shiv.js',
'../../libs/respond/dest/respond.min.js',
'../../libs/jquery/dist/jquery.min.js'
]
};
copy: {
build_libjs: {
files: [
{
src: [ '<%= lib_files.js %>' ],
dest: '<%= build_dir %>/',
cwd: '.',
expand: true
}
]
},
},
At the moment it copies all the files over to apps/libs because of the '../../' each file has in the lib_files.js array. How can I make sure that the files end up in the build folder like so?:
-apps
-exampleApp1
-GruntFile.js
-build
-libs
-html5shiv/dist/html5shiv.js
-libs/respond/dest/respond.min.js
-jquery/dist/jquery.min.js
The answer is quite simple actually. There is a rename function which can be used in combination with grunt-contrib-copy.
"You just need to attach one parameter to my configuration, which overrides the standard rename function of the Grunt file utilities.".
from:
http://fettblog.eu/blog/2014/05/27/undocumented-features-rename/
I combined this with a simple regular expression and problem solved:
build_libjs: {
files: [
{
src: [ '<%= lib_files.js %>' ],
dest: '<%= build_dir %>/',
cwd: '.',
expand: true,
rename: function(dest, src) {
//Replace '../../' with an empty string
return dest + ( src.replace(/^..\/..\// ,"") );
}
}
]
},
Try using the cwd property to change the source directory
lib_files: {
js: [
'html5shiv/dist/html5shiv.js',
'respond/dest/respond.min.js',
'jquery/dist/jquery.min.js'
]
};
copy: {
build_libjs: {
files: [
{
src: [ '<%= lib_files.js %>' ],
dest: '<%= build_dir %>/',
cwd: '../libs',
expand: true
}
]
},

Resources