Webpack vendor bundling - node.js

I've created a vendor bundle of all my third party scripts. I'm referencing the new vendor.bundle.js into my index.html file.
It seems as though none of the third party scripts are actually accessible from my main.js file. Any ideas what I'm potentially doing incorrectly?
webpack.config.js
var CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
module.exports = {
entry: {
vendor: ['babel-polyfill', 'jquery', 'jquery-match-height'],
main: './src/main.js'
},
output: {
path: './dist',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/, loader: 'babel', exclude: /node_modules/,
query: { plugins: ['transform-runtime'], presets: ['es2015'] }
}
]
},
plugins: [
new CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js")
]
};

Related

asset_url_for() returns None in flask cookie cutter (flask-webpack)

Im new to webpack. Im using flask-cookie-cutter which in turn uses Flask-Webpack
Im having issues in that App wont find my images in development.
Images are in assets/img folder
Ive tried using {{ asset_url_for('img/img_name.png') }} and various variations of it - and it just returns none.
Ive tried the usual flask way of {{ url_for('static', filename='img/img_name.png') }}
But I cant seem to access them.
const path = require('path');
const webpack = require('webpack');
/*
* Webpack Plugins
*/
const ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://0.0.0.0:2992' : '';
const rootAssetPath = path.join(__dirname, 'assets');
module.exports = {
// configuration
context: __dirname,
entry: {
main_js: './assets/js/main',
main_css: [
path.join(__dirname, 'node_modules', 'materialize-css', 'dist', 'css', 'materialize.css'),
path.join(__dirname, 'assets', 'css', 'style.css'),
],
},
output: {
path: path.join(__dirname, 'dsi_website', 'static', 'build'),
publicPath: `${publicHost}/static/build/`,
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].js',
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
},
devtool: 'source-map',
devServer: {
headers: { 'Access-Control-Allow-Origin': '*' },
},
module: {
rules: [
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader!less-loader',
],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader',
],
},
{
test: /\.html$/,
loader: 'raw-loader'
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
{
test: /\.(ttf|eot|svg|png|jpe?g|gif|ico)(\?.*)?$/i,
loader: `file-loader?context=${rootAssetPath}&name=[path][name].[hash].[ext]`
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env'],
cacheDirectory: true
}
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[hash].css', }),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new ManifestRevisionPlugin(path.join(__dirname, 'dsi_website', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
]),
};
I was the same problem with flask-cookie-cutter and solve it by update/upgrade npm and add extensionsRegex: /\.(jpe?g|png|gif|svg)$/i at down file: webpack.config.js like this:
ManifestRevisionPlugin(path.join(__dirname, '<your app>', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
extensionsRegex: /\.(jpe?g|png|gif|svg)$/i
}),
source solution. Proper call to show image in temaplate:
{{ asset_url_for('img/img_name.png') }}
after that i check startup screen and i see that all my images load properly
[WEBPACK] _/assets/img/image_name.20aed528d50316c91ffedb5ba47b8c74.jpg 18.9 KiB [emitted]

Webpack 2 - Problems parsing node_module

I'm unit testing with mocha-webpack v1.0.1, node v6.10. However, I'm getting an error from one of our node modules, where webpack couldn't parse a #. This is an internal library that we use that runs fine in another development environment. So, I'm confused why this is happening since you would think that a library in your node_module would be sort of self-sustaining and would know how to parse itself (and is validated as working in another environment).
Error in ./~/abc-components/src/abc-theme/index.scss
Module parse failed: /path/to/app/node_modules/abc-components/src/abc-theme/index.scss Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #charset "UTF-8";
| #import "abc-variables";
| #import "alert";
I believe # is an alias we use for resolving the module path in that library. I've modeled my setup after this tutorial.
From package.json:
"unit": "BABEL_ENV=test mocha-webpack --webpack-config build/webpack.test.conf.js --require test/unit/.setup src/**/*.spec.js --recursive --watch"
From build/webpack.test.conf.js config, including some comments of things I've tried:
var path = require('path')
var webpack = require('webpack')
var utils = require('./utils')
var config = require('../config')
// var nodeExternals = require('webpack-node-externals');
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
resolve: {
modules: [path.resolve('./src'), "node_modules"],
extensions: ['.js', '.vue', '.json', '.ts'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
// externals: [nodeExternals()],
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
// plugins: [
// new webpack.optimize.CommonsChunkPlugin({
// name: "vendor",
// filename: "vendor.js",
// minChunks: function (module) {
// // This prevents stylesheet resources with the .css or .scss extension
// // from being moved from their original chunk to the vendor chunk
// if(module.resource && (/^.*\.(css|scss)$/).test(module.resource)) {
// return false;
// }
// return module.context && module.context.indexOf("node_modules") !== -1;
// }
// }),
// new webpack.DefinePlugin({
// 'process.env': require('../config/test.env')
// })
// ],
module: {
loaders: [
{
test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// enforce: 'pre',
include: [resolve('src'), resolve('test'), resolve('node_modules')],
/* options: {
formatter: require('eslint-friendly-formatter')
} */
},
{
test: /\.pug$/,
loader: 'pug-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader'
// options: vueLoaderConfig
},
{
test: /\.ts$/,
loader: "awesome-typescript-loader",
include: [resolve('src'), resolve('test')]
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
},
include: [resolve('src'), resolve('test')]
// exclude: /node_modules/
},
{
test: /\.(mp3|wav)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('audio/[name].[hash:7].[ext]')
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
resolveLoader: {
alias: {
// necessary to to make lang="scss" work in test when using vue-loader's ?inject option
// see discussion at https://github.com/vuejs/vue-loader/issues/724
'scss-loader': 'sass-loader'
}
}
}
Include following config in loader.
module: {
loaders: [
{
test: /\.(scss|sass)$/i,
include: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'path/to/imported/file/dir'), <== This solved the issue
],
loaders: ["css", "sass"]
},
]
},

Webpack suppress eslint warnings on browser console

I`ve finished configuring my eslint rules and refactoring project files according to my rules. Thing is that I have some warnings that I may want to leave there for a while. But my problem is that warnings are being shown on browser console, what makes development impossible.
Below, my webpack config:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const context = path.resolve('.');
module.exports = {
context: context,
entry: './src/client.js',
output: {
path: path.join(context, 'build/client'),
publicPath: '/static/',
filename: '[name]-[hash].js'
},
module: {
preLoaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
],
loaders: [{
test: /(?:node_modules).+\.css$/,
loader: 'style!css'
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract([
'css-loader',
'postcss-loader',
'sass-loader',
'sass-resources'
])
}, {
test: /\.js$/,
loader: 'babel',
exclude: /(node_modules)/
}, {
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file"
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
}, {
test: /\.json$/,
loader: 'json'
}]
},
postcss: function() {
return [
require('autoprefixer')
];
},
sassResources: [
path.resolve(__dirname, '../src/stylesheets/base/_variables.scss'),
path.resolve(__dirname, '../src/stylesheets/base/_mixins.scss')
],
devServer: {
watchOptions: {
aggregateTimeout: 1000
}
},
plugins: [
new ExtractTextPlugin("[name]-[hash].css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'local')
})
],
devtool: "cheap-module-source-map"
};
I have no problem with errors being displayed on browser console, but is there a way to suppress warnings ONLY on browser console and not on the node terminal?
https://devhub.io/repos/coryhouse-eslint-loader
In my webpack.config.js I have options setup:
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['es2015', {modules: false}],
'react'
],
plugins: [ 'react-hot-loader/babel' ]
}
}, {
loader: 'eslint-loader',
options: {
quiet: true
}
}
]
}
]
}
The last line is quiet: true, which is how it suppresses the warnings.
Use
clientLogLevel: "none"
in the devServer config
Doc: https://webpack.js.org/configuration/dev-server/#devserverclientloglevel
devServer.clientLogLevel
string: 'none' | 'info' | 'error' | 'warning'
When using inline mode, the console in your DevTools will show you messages e.g. before reloading, before an error or when Hot Module Replacement is enabled. Defaults to info.
devServer.clientLogLevel may be too verbose, you can turn logging off by setting it to 'none'.
webpack.config.js
module.exports = {
//...
devServer: {
clientLogLevel: 'none'
}
};
Usage via the CLI
webpack-dev-server --client-log-level none

Webpack not including ProvidePlugins

I have a small trial web application that I'm working on that uses the vue webpack template (https://github.com/vuejs-templates/webpack). I'm pretty new to webpack so I was assuming that I could add in to plugins a new webpack.ProvidePlugin and it would be available globally but when I do a npm run dev I get the following error:
/var/www/public/leadsStatsDashboard/liveleadstats/src/components/Hello.vue
18:17 error 'd3' is not defined no-undef
Which sounds like to me that it can't find the d3 reference. I'm no sure if there's some configuration I skipped over or what but any help would be appreciated. Here is the source for my files
Webpack.dev.conf.js:
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var projectRoot = path.resolve(__dirname, '../')
module.exports = {
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
crossfilter: 'crossfilter',
dc: 'dc'
})
],
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
publicPath: config.build.assetsPublicPath,
filename: '[name].js'
},
resolve: {
extensions: ['', '.js', '.vue'],
fallback: [path.join(__dirname, '../node_modules')],
alias: {
'src': path.resolve(__dirname, '../src'),
'assets': path.resolve(__dirname, '../src/assets'),
'components': path.resolve(__dirname, '../src/components'),
'd3': path.resolve(__dirname, '../bower_components/d3/d3.min.js'),
'crossfilter': path.resolve(__dirname, '../bower_components/crossfilter/crossfilter.min.js'),
'dc': path.resolve(__dirname, '../bower_components/dcjs/dc.js')
}
},
resolveLoader: {
fallback: [path.join(__dirname, '../node_modules')]
},
module: {
preLoaders: [
{
test: /\.vue$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.js$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
}
],
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.html$/,
loader: 'vue-html'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
eslint: {
formatter: require('eslint-friendly-formatter')
},
vue: {
loaders: utils.cssLoaders()
}
}
Hello.vue
<template>
<div id="pieChartContainer">
</div>
</template>
<script>
export default {
data () {
return {
// note: changing this line won't causes changes
// with hot-reload because the reloaded component
// preserves its current state and we are modifying
// its initial state.
msg: 'Hello World! This is a test'
}
},
ready () {
console.log(d3.version)
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
color: #42b983;
}
</style>
Your error isn't emitted from webpack, but from eslint.
I think the webpack part works as it should, in fact!
no-undef complains that you are using the global d3 without importing or defining it somewhere.
The good news is, that's easy to fix. Use any of the following three possibilities:
Just add the following block to your .eslintrc.js:
"globals": {
"d3": true
}
...or use eslint comments within the file that requires d3 implicitly (but that doesn't make much sense as you made it available globally and you would need to do this in every file you wish to use the global var):
/* eslint-disable no-undef */
...or you could relax the eslint rule in your .eslintrc.js config:
'rules': {
// all other rules...
'no-undef': 0
}
Additional links:
Direct link to the template's eslintrc file
The eslint 'standard' file the template extends
Further reading on eslint's no-undef rule

Building server part of (React) isomorphic webapp with webpack including style-loader for CSS

I am attempting to make a React application that I am developing isomorphic. One of the known problems with doing this is that webpack loaders allow import/require of non-javascript assets such as CSS files. e.g.
// ExampleComponent.jsx
import Select from 'react-select';
import 'react-select/dist/react-select.css';
If building an application with Express then node will get to this import and fail because it can not process a CSS file, it is expecting javascript only (and thanks to babel-register JSX).
One of the ways around this is to use the target: 'node' option in webpack when building the server application (which includes all the common parts such as the components as it is an isomorphic app) to build the server side code. This should result in a server.js being built that can then be run by node.
Note: I know that there are other ways around this particular problem (such as not using import/require to include anything that isn't javascript, but that isn't practical at this stage of development in this application.
// webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = [
// Client build
{
entry: {
'bundle.min': [
'bootstrap-webpack!./bootstrap.config.js',
'babel-polyfill',
'./client/index.jsx'
],
'bundle': [
'bootstrap-webpack!./bootstrap.config.js',
'babel-polyfill',
'./client/index.jsx'
]
},
output: {
path: './dist',
filename: '[name].js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})
],
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
plugins: ['transform-runtime'],
presets: ['react', 'es2015', 'stage-0']
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0']
}
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{ test: /\.png$/,
loader: "url-loader?limit=100000"
},
// Bootstrap
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.json']
}
},
// Server build
{
entry: './server/server.jsx',
target: 'node',
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
},
output: {
path: './dist',
filename: 'server.js',
},
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
plugins: ['transform-runtime'],
presets: ['react', 'es2015', 'stage-0']
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0']
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{ test: /\.png$/,
loader: "url-loader?limit=100000"
},
// Bootstrap
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.json']
}
}
];
The problem is then that the style-loader makes use of window which obviously does not exist in the node environment.
$ node dist/server.js
/Users/dpwrussell/Checkout/ExampleApp/dist/server.js:25925
return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
^
ReferenceError: window is not defined
From here in style-loader.
It feels like I am very close to making this work so any thoughts would be welcome.
The answer is not to use style-loader in your server build: its sole purpose is to take CSS, turn it into a <style> element, and insert it into the DOM. Most people seem to use the ExtractTextPlugin to collect their CSS for inclusion on the server side.

Resources