Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Webpack assets and global styles.css

In a former project I used angular-cli to build my project. Now I have to use webpack directly, within a .NET project. And I'm struggling to get a simple thing work:

  • Use a global style.css app wide
  • Copy my assets folder to dist

My build output directory is wwwroot/dist (our project requirement).

Angular-cli had a nice "simplified" config:

"outDir": "../wwwroot/dist",
"assets": [
        "assets"
      ],
"styles": [        
        "styles.css"
      ],

And with that I ended with a correct dist folder, my assets where move to the proper output directory, and my styles.css at app level was available anywhere in my app.

Now, i can't manage how to configure webpack to get this work in the new project structure and configuration. I think my team started the project using VS2015 templates, which produce a generic structure: https://github.com/aspnet/JavaScriptServices/tree/dev/templates/Angular2Spa

My project structure:

Project Structure

My two webpack config files

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];

Also have a vendor config to build vendors separately and refresh them less often. I don't want my assets and global style.css to be on vendor part.

webpack.config.vendor.js

var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');

module.exports = {
    resolve: {
        extensions: [ '', '.js' ]
    },
    module: {
        loaders: [
            { test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader?limit=100000' },
            { test: /\.css(\?|$)/, loader: extractCSS.extract(['css']) }
        ]
    },
    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',
            'bootstrap',
            'bootstrap/dist/css/bootstrap.css',
            'bootstrap-filestyle',
            'font-awesome/css/font-awesome.css',
            'es6-shim',
            'es6-promise',
            'jquery',
            'zone.js',
        ]
    },
    output: {
        path: path.join(__dirname, 'wwwroot', 'dist'),
        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]'
        })
    ].concat(isDevBuild ? [] : [
        new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
    ])
};

I'd like to be able to use the css in defined in styles.css application wide and my assets to be moved in wwwroot/dist. I want to access them in my app by loading /dist/assets/xxx

like image 264
BlackHoleGalaxy Avatar asked Dec 23 '16 19:12

BlackHoleGalaxy


1 Answers

Was looking through some webpack questions and came across this. Though its really old and you probably found a work around, I still want to propose a solution.

Webpack uses loaders for various file types that gets required/imported in your code. Seeing that you already have loaders specified for css & images, I'm guessing that you arent directly requiring/importing any of the above mentioned assets in your javascript code, but rather just referring to them in your css or html.

In which case you could use a webpack plugin like copy-webpack-plugin, to copy over these assets to your build directory. Would be something like this:

//webpack.config.js

var CopyWebpackPlugin = require('copy-webpack-plugin');
...
config.plugins = config.plugins.concat([
  new CopyWebpackPlugin([
    { from: 'assets', to: '../wwwroot/dist/assets' }
  ]),
...
]);
like image 191
Gerhard Mostert Avatar answered Nov 10 '22 19:11

Gerhard Mostert