Webpack, how to take out module into his own build layer? - build

With default build settings I get following build layers:
(X+A), (Y+A+B), (Z+B).
I want:
(X+A), (Y+A), Z, B
B should load only once when we asking Y and Z modules.
I found CommonsChunkPlugin, but I cant configure it properly.
var webpack = require("webpack");
var CommonsPlugin = new require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
entry: {
main: "./main"
},
resolve: {
modulesDirectories: [
"."
]
},
output: {
publicPath: "js/",
filename: "[name].builded.js"
},
plugins: [
new CommonsPlugin({
// What should I write here?
})
]
};

Looks like you should add B as separate entry point:
entry: {
main: "./main",
Bentry: ["B"]
},
and add CommonsChunkPlugin in plugins section:
new webpack.optimize.CommonsChunkPlugin('Bentry', 'B.js'),

Related

webpack 4 images in node_modules : module not found

The problem
Im using webpack 4 to compile scss to css and MiniCssExtractPlugin to save the css into a different file. The problem is, that i dont manage to load images and fonts, that are included via url() inside of the scss files. It also makes no difference between running development or production.
Scss is compiled perfectly and without any problems. Also the scss-loader has no problems loading .scss-files from node_modules.
Why does this error occur and how can i fix it?
error-message when running npm
ERROR in ./ui/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./ui/index.scss)
Module not found: Error: Can't resolve '../webfonts/fa-solid-900.woff' in '/home/asdff45/Schreibtisch/Programme/GO/src/factorio-server-manager/manager/ui'
# ./ui/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./ui/index.scss) 7:336881-336921
ERROR in ./ui/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./ui/index.scss)
Module not found: Error: Can't resolve '../webfonts/fa-solid-900.woff2' in '/home/asdff45/Schreibtisch/Programme/GO/src/factorio-server-manager/manager/ui'
# ./ui/index.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./ui/index.scss) 7:336799-336840
And multiple more, but all have the same error, just the filename changes.
webpack-Config
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
// js: './ui/index.js',
sass: './ui/index.scss'
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'app')
},
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'ui/js/')
},
extensions: ['.js', '.json', '.jsx']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
},
{
test: /(\.(png|jpe?g|gif)$|^((?!font).)*\.svg$)/,
loaders: [
{
loader: "file-loader",
options: {
name: loader_path => {
if(!/node_modules/.test(loader_path)) {
return "app/images/[name].[ext]?[hash]";
}
return (
"app/images/vendor/" +
loader_path.replace(/\\/g, "/")
.replace(/((.*(node_modules))|images|image|img|assets)\//g, '') +
'?[hash]'
);
},
}
}
]
},
{
test: /(\.(woff2?|ttf|eot|otf)$|font.*\.svg$)/,
loaders: [
{
loader: "file-loader",
options: {
name: loader_path => {
if (!/node_modules/.test(loader_path)) {
return 'app/fonts/[name].[ext]?[hash]';
}
return (
'app/fonts/vendor/' +
loader_path
.replace(/\\/g, '/')
.replace(/((.*(node_modules))|fonts|font|assets)\//g, '') +
'?[hash]'
);
},
}
}
]
}
]
},
performance: {
hints: false
},
plugins: [
new MiniCssExtractPlugin({
filename: "bundle.css"
})
]
}
Project Repo/Branch
You need to add resolve-url-loader to your build, like this:
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"resolve-url-loader",
"sass-loader?sourceMap"
]
}
resolve-url-loader is resolving paths to assets based on the original file that is importing the asset.
I tried it locally and the build is now passing :) Cheers!

Build failure while using Webpack4 in AngularJS1.5.11

I am working on an AngularJS Project to configure webpack for bundling purpose. I am using webpack4 for the same.
Below is the config file.
webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');// Require html-webpack-plugin plugin
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const ExtractNormalCSS = new ExtractTextPlugin("./src/main/frontend/sass/main.scss");
const extractCSS = new ExtractTextPlugin('/src/main/frontend/assets/icons/paas-icons/style.css');
module.exports = {
entry: [ "./src/main/frontend/app/app.js","./src/main/frontend/sass/main.scss"], // webpack entry point. Module to start building dependency graph
output: {
path: path.join(__dirname, '/distTemp/'), // Folder to store generated bundle
filename: '[name].bundle.js' // Name of generated bundle after build
//publicPath: '' // public URL of the output directory when referenced in a browser
},
resolve:{
modules: [
'node_modules',
'bower_components',
'src'
],
extensions:[".js"]
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
compact: false,
cacheDirectory: true,
presets: ['es2015', 'angular'],
},
},
{
test: /.(scss)$/,
loader: 'style-loader!css-loader!sass-loader'
},
{
test: /\.html$/,
loader: 'html-loader?name=views/[name].[ext]'
},
{
test: /\.(png|jpg)$/,
use: [
'url-loader?limit=8192'
]
},
]
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: false
},
sourceMap: true
})
],
splitChunks: {
cacheGroups: {
commons: {
test: /node_modules/,
name: 'vendor',
chunks: 'all'
}
}
}
},
plugins: [ // Array of plugins to apply to build chunk
new HtmlWebpackPlugin({
template: "./src/main/frontend/index.html",
inject: 'body'
}),
new ExtractTextPlugin('/distTemp/style/style.css'),
ExtractNormalCSS,
extractCSS
],
devServer: { // configuration for webpack-dev-server
contentBase: '.src/main/frontend/assets', //source of static assets
port: 7700, // port to run dev-server
}
};
Upon building, I am getting the error mentioned below.
ERROR in ./src/main/frontend/sass/main.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/main/frontend/sass/main.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
var path = require("path");
^
Invalid CSS after "v": expected 1 selector or at-rule, was "var path = require("
in ###/node_modules/bourbon/index.js (line 1, column 1)
Error:
var path = require("path");
^
Invalid CSS after "v": expected 1 selector or at-rule, was "var path = require("
in ###/node_modules/bourbon/index.js (line 1, column 1)
at options.error (###/node_modules/node-sass/lib/index.js:291:26)
# ./src/main/frontend/sass/main.scss 2:14-134
# multi ./src/main/frontend/app/app.js ./src/main/frontend/sass/main.scss
I am using sass-loader and node-sass for the .scss files.
The main.scss file contains imports for the rest of the style files.
Could someone assist me in resolving this error please?

Using Webpack's Coffee-Loader without explicitly stating ".coffee" file extension

preface
I am currently switching our build process over from Browserify to Webpack. As the project uses a great deal of coffee-script, I have many import statements such as:
require('./coffee-file-without-extension') # note the lack of .coffee
require('./legacy-js-file-without-extension') # note the lack of .js
problem
Browserify handles the absence of the file extension just fine. Webpack seems to have issue per this error:
Module not found: Error: Can't resolve './wptest-req' in '/Users/jusopi/Dev/Workspaces/nx/nx-ui/src'
I setup a super simple test project for this where I have the following files:
wptest.coffee
require('./wptest-req')
wptest-req.coffee
module.exports = {}
webpack.config.js
const path = require('path');
const webpack = require('webpack')
module.exports = {
entry: {
main: './src/wptest.coffee'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
})
],
module: {
rules: [
{
test: /\.coffee$/,
use: [
{
loader: 'coffee-loader',
options: { sourceMap: true }
}
]
}
]
}
};
end-goal
I am hoping I do not have to go over every file in our application and append .coffee to all require statements for coffee files if at all possible.
While this solution is not specific to coffee-loader, it did resolve my issue. I needed to add a resolve object to my configuration:
const path = require('path');
const webpack = require('webpack')
module.exports = {
entry: {
main: './src/main.coffee'
// other: './src/index2.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
})
],
module: {
rules: [
{
test: /\.coffee$/,
use: [
{
loader: 'coffee-loader',
options: { sourceMap: true }
}
]
}
]
},
resolve: {
extensions: [ '.coffee', '.js' ]
}
};
src - https://github.com/webpack-contrib/coffee-loader/issues/36

How to load babel-plugin-react-intl using babel-loader?

I recently initialized a react app using create-react-app.
I ejected the app and I now have all the files exported to my main directory.
This set up creates a babel.dev.js instead of using .babelrc (it uses babel-loader).
I am trying to figure out how do I configure react-intl and babel-plugin-react-intl without the .babelrc file.
The documentation says .babelrc is recommended
Via .babelrc (Recommended)
.babelrc
{
"plugins": [
["react-intl", {
"messagesDir": "./build/messages/"
}]
]
}
What is the syntax to have this behavior with babel-loader? Right now the plugins in babel.dev.js look like this:
plugins: [
// class { handleClick = () => { } }
require.resolve('babel-plugin-transform-class-properties'),
// { ...todo, completed: true }
require.resolve('babel-plugin-transform-object-rest-spread'),
// function* () { yield 42; yield 43; }
[require.resolve('babel-plugin-transform-regenerator'), {
// Async functions are converted to generators by babel-preset-latest
async: false
}],
// Polyfills the runtime needed for async/await and generators
[require.resolve('babel-plugin-transform-runtime'), {
helpers: false,
polyfill: false,
regenerator: true,
// Resolve the Babel runtime relative to the config.
// You can safely remove this after ejecting:
moduleName: path.dirname(require.resolve('babel-runtime/package'))
}]
]
My components currently have the strings defined as follows:
const messages = defineMessages({
summaryTitle: {
"id": "checkout.section.title.summary",
"description": "Summary Section Title",
"defaultMessage": "Summary"
},
shippingTitle: {
"id": "checkout.section.title.shipping",
"description": "Shipping Section Title",
"defaultMessage": "Shipping"
}
});
Add the babel-plugin-react-intl to your plugins array like this:
plugins: [
..., // some plugins here
[require.resolve('babel-plugin-react-intl'), { messageDir: "./build/messages"}]
]
This will load the plugin passing the messageDir as an option to it.

How to get code coverage numbers accurate with isparta, webpack, jasmine and karma?

I am having difficulty getting the correct code coverage numbers when trying to use a combination of webpack, isparta, jasmine and karma. The numbers at the end of a test run do not reflect the ES6 code correctly. However, the UI shows the correct ES6 file, with the correct highlighting, just not the correct numbers.
Here is a screenshot of what I am talking about.
Wrong Code Coverage Numbers:
The code and highlighting is correct, but the numbers are not. For example, the Statement number is completely off. I am assuming these numbers are coming from the transpiled code.
Here is my karma.config.js:
'use strict';
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var webpackConfig = require('./webpack.config.js');
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
var dependencies = wiredep(wiredepOptions).js;
dependencies.push('test-context.js');
return dependencies;
}
module.exports = function(config) {
var configuration = {
files: listFiles(),
logLevel: 'WARN',
frameworks: ['jasmine'],
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-coverage',
'karma-jasmine',
'karma-webpack'
],
preprocessors: {
'test-context.js': ['webpack']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
reporters: ['progress', 'coverage'],
coverageReporter: {
dir : 'coverage/',
reporters: [
{ type: 'html' }
]
}
};
config.set(configuration);
};
Here is my webpack config:
var webpack = require('webpack');
module.exports = {
node: {
fs: 'emtpy'
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'isparta',
include: /(src)/
}
],
loaders: [
{
test: /\.js$/,
include: /(src)/,
loader: 'babel?stage=0'
}
]
},
resolve: {
extensions: [
'',
'.js'
]
},
devtool: 'inline-source-map'
};
Here is the test.context.js:
var context = require.context('./test', true, /\.js$/);
context.keys().forEach(context);
var srcContext = require.context('./src', true, /\.js$/);
srcContext.keys().forEach(srcContext);
If you have a GitHub account you can see this list of real projects which use webpack with isparta, jasmine, and karma for a set of working examples to compare against. Hope this helps, thanks.