Unexpected character '#' You may need an appropriate loader to handle this file type - javascript

This is what I get when I try to run webpack: the error I get is:
"ERROR in ./v3/app/styles/main.scss
Module parse failed: /Users/vovina/widget-login-react/v3/app/styles/main.scss Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type."
it can't resolve #import, any ideas on this?
my webpack config is as follow:
const childProcess = require('child_process')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const trimEnd = require('lodash/trimEnd')
const webpack = require('webpack')
const path = require('path')
const ENV = {
NODE_ENV: process.env.NODE_ENV,
API: 'https://accounts' + (process.env.NODE_ENV === 'prd' ? '' : '-'
+ process.env.NODE_ENV),
BUILD_VERSION: trimEnd(childProcess.execSync('git rev-list HEAD --
count').toString(), '\n'),
BUILD_DATE: trimEnd(childProcess.execSync('git log --format="%cd" -n
1').toString(), '\n'),
BUILD_COMMIT_ID: trimEnd(childProcess.execSync('git log --format="%h"
-n 1').toString(), '\n')
}
const prodLikeEnvironment = process.env.NODE_ENV === 'stg' ||
process.env.NODE_ENV === 'prd'
const CSS_MAPS = !prodLikeEnvironment
module.exports = {
entry: {
init: [
'./app/init.js'
],
login: [
'./app/login.js'
],
authentication: [
'./v3/app/authenticator.js'
],
common: [
'./app/common.js'
]
},
target: 'web',
output: {
path: path.join(__dirname, 'dist', process.env.NODE_ENV),
pathinfo: true,
publicPath: '/assets/widgets/login/v2/',
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js',
libraryTarget: 'umd'
},
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat'
},
modules: [
path.resolve('./app'),
path.resolve('./node_modules')
]
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: [/bower_components/, /node_modules/]
},
{
// Transform our own .(scss|css) files with PostCSS and CSS-modules
test: /\.(scss|css)$/,
include: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?modules&importLoaders=1&localIdentName=
[local]${process.env.CSS_MODULES_IDENT ||
'_[hash:base64:5]'}&sourceMap=${CSS_MAPS}`,
'postcss-loader',
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(scss|css)$/,
exclude: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?sourceMap=${CSS_MAPS}`,
`postcss-loader`,
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(svg|eot|woff|woff2?|ttf|otf)$/,
use: 'base64-font-loader'
},
{
test: /.json$/,
loader: 'json'
},
{
test: /\.jpe?g$|\.gif$|\.png$/,
use: 'base64-image-loader'
},
{
test: /\.html?$/,
loader: 'html'
},
{
test: /\.js$/,
loader: 'strip-loader?strip[]=debug,strip[]=console.log,strip[]=console.debug,strip[]=console.info'
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true
// postcss: [
// autoprefixer({ browsers: 'last 2 versions' })
// ]
}),
new CopyWebpackPlugin([
{ from: 'public' }
]),
new ExtractTextPlugin('[name].bundle.css'),
new webpack.DefinePlugin({
ENV: JSON.stringify(ENV),
// Only used for react prod bundle. Refer to ENV.NODE_ENV for business
logic
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
unsafe_comps: true,
properties: true,
keep_fargs: false,
pure_getters: true,
collapse_vars: true,
unsafe: true,
warnings: false,
screw_ie8: true,
sequences: true,
dead_code: true,
drop_debugger: true,
comparisons: true,
conditionals: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
hoist_funs: true,
if_return: true,
join_vars: true,
cascade: true,
drop_console: true
}
})
]
}

You are using the (scss|css) twice in your configuration file.
Remove that and use the code posted blow:
Before using, you must first npm install raw-loader.
I think you've already installed the sass-loader.
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
},
// // css global which not include in components
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: 'raw-loader'
})
},
{
test: /\.scss$/,
include: helpers.root('src', 'app'),
use: ['raw-loader', 'sass-loader']
},
// // SASS global which not include in components
{
test: /\.scss$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: ['raw-loader', 'sass-loader']
})
}
Add my root()function.
var path = require('path');
var _root = path.resolve(__dirname, '..');
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [_root].concat(args));
}
exports.root = root;
Hope this will work.

Related

Optimize bundle.js file size

Below is the webpack config code and it's size is around 6.2 MB. In production mode it looks more time load the signin page url and from second time onwards it looks good , the problem with first time and need suggestion to reduce the bundle.js file size
webpack.base.js
module.exports = {
//Running babel to every file
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [
'react',
'stage-0',
['env', { targets: { browsers: ['last 2 versions'] } }]
]
}
}, {
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.less$/,
use:[
{
loader: "style-loader"
},
{
loader: 'css-loader'
},
{
loader: "less-loader"
}
]
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg|otf)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=100000'
}
]
}//end module
}
webpack.client.js:
const config = {
entry: './src/client/client.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
}
};
module.exports = merge(baseConfig, config)
webpack.server.js:
const server_config = {
//letting webapck know that this bundle is created for node server.
target: 'node',
entry: './src/server/server.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
externals: [webpackNodeExternals()],
node:{
__dirname:false
}
};
module.exports = merge(baseConfig, server_config);
Here is how I optimize webpack. You can view my full config here
First you need to run webpack production mode when you want to build in production
webpack -p --mode=production
Below is minial config
const path = require("path");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const WebpackShellPlugin = require('webpack-shell-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
module.exports = {
optimization: {
minimizer: [
new UglifyJsPlugin({ // minify js file
cache: true,
parallel: true,
sourceMap: false,
extractComments: 'all',
uglifyOptions: {
compress: true,
output: null
}
}),
new OptimizeCSSAssetsPlugin({ // minify css
cssProcessorOptions: {
safe: true,
discardComments: {
removeAll: true,
},
},
})
]
},
plugins: [
new CompressionPlugin({ // gzip js and css
test: /\.(js|css)/
}),
new UglifyJsPlugin(), // uglify js
new WebpackShellPlugin({
onBuildStart: ['echo "Starting postcss command"'],
onBuildEnd: ['postcss --dir wwwroot/dist wwwroot/dist/*.css'] // uglify css using postcss
})
],
module: {
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader", "eslint-loader"]
},
{
test: /\.(jpe?g|png|gif)$/i,
loader: "file-loader"
},
{
test: /\.(woff|ttf|otf|eot|woff2|svg)$/i,
loader: "file-loader"
}
]
}
};

My Vue build in webpack produces a huge (850kb) vendor file, how do I make it the expected 85kb?

Solved:
devtool: '#eval-source-map'
Includes a source map in the output
Original issue
As stated, the webpack build produces an enormous bundle/vendor file with Vue as my only import. I cannot see for the life of me how people get it down to 80kb.
As far as I can see, there is a vue-loader and the file gets minified, so why would it come out enormous?
var path = require('path') var webpack = require('webpack')
module.exports = { entry: './src/main.js', output: {
path: path.resolve(__dirname, './static'),
publicPath: '/static/',
filename: 'js/login-view.js' }, module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
useRelativePath: true,
publicPath: './static/images/'
}
}
] }, resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json'] }, devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true }, performance: {
hints: false }, devtool: '#eval-source-map' }
if (process.env.NODE_ENV === 'production') { // module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
// compress: true,
compress: {
warnings: false
},
mangle: true,
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}) ]) }
devtool: '#eval-source-map'
was the culprit. It was getting included in all builds and it puts the sourcemap in the files. I removed this and dropped the file to ~90kb.

Lazy Loading not work in WebPack Angular 2 project

I'm new to webPack and I have a problem with my project in Angular 2.
I'm trying to apply Lazy Loading on the modules, but I have always the same mistake for hours.
The error occurs when i need to load a child module. (During the rooting)
export const routes: Routes =
[
{ path: '', redirectTo: '/account', pathMatch: 'full' },
{ path: 'account', component: LoginComponent },
{ path: 'student', canLoad: [AuthGuard], loadChildren: './student.module/app.student.module#AppStudentModule' },
{ path: 'teacher', canLoad: [AuthGuard], loadChildren: './teacher.module/app.teacher.module#AppTeacherModule' },
{ path: 'administrative', canLoad: [AuthGuard], loadChildren: './secretary.module/app.secretary.module#AppSecretaryModule' },
{ path: 'unauthorized', component: PageUnauthorized },
{ path: 'terms', component: TermsComponent},
{ path: '**', component: PageNotFound }
];
I show you my current configuration:
My webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
const root = path.join.bind(path, path.resolve(__dirname));
// Webpack Config
const webpackConfig = {
entry: {
app: './src/main.ts',
polyfills: './src/polyfills.ts',
vendor: './src/vendor.ts'
},
output: {
publicPath: '/public/js',
path: path.resolve(__dirname, './public/js')
},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
root('./src'), // location of your src
{} // a map of your routes
),
new webpack.ProvidePlugin({
'lodash': 'lodash',
'moment': 'moment',
'moment-timezone': 'moment-timezone',
'angular2-mdl': 'angular2-mdl',
'jquery': 'jquery'
}),
new CopyWebpackPlugin([ { from: 'src/assets/i18n', to: '/assets/i18n' } ]),
new ExtractTextPlugin('../css/styles.css')
],
module: {
loaders: [
{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader',
'angular2-router-loader',
'angular2-template-loader'
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader?minimize=true'
}),
include: [root('assets', 'css'), /node_modules/]
},
{
test: /\.scss$/,
loader: 'raw-loader!sass-loader'
},
{test: /\.html$/, loader: 'raw-loader'},
{ test: /\.(png|jpg|woff|woff2|eot|ttf|TTF|svg)$/, loader: 'url-loader?limit=100000' }
]
}
};
const defaultConfig = {
devtool: 'source-map',
output: {
filename: '[name].js',
sourceMapFilename: '[name].map',
chunkFilename: '[name]-chunk.js'
},
resolve: {
extensions: [ '.ts', '.js' ],
modules: [ path.resolve(__dirname, 'node_modules') ]
},
node: {
global: true,
crypto: 'empty',
__dirname: true,
__filename: true,
process: true,
Buffer: false,
clearImmediate: false,
setImmediate: false
}
};
const commonConfig = webpackMerge(defaultConfig, webpackConfig);
const prodConfig = {
devtool: 'source-map',
plugins: [
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
sequences : true, // join consecutive statemets with the “comma operator”
properties : true, // optimize property access: a["foo"] → a.foo
dead_code : true, // discard unreachable code
drop_debugger : true, // discard “debugger” statements
unsafe : false, // some unsafe optimizations (see below)
conditionals : true, // optimize if-s and conditional expressions
comparisons : true, // optimize comparisons
evaluate : true, // evaluate constant expressions
booleans : true, // optimize boolean expressions
loops : true, // optimize loops
unused : true, // drop unused variables/functions
hoist_funs : true, // hoist function declarations
hoist_vars : false, // hoist variable declarations
if_return : true, // optimize if-s followed by return/continue
join_vars : true, // join var declarations
cascade : true, // try to cascade `right` into `left` in sequences
side_effects : true, // drop side-effect-free statements
warnings : true, // warn about potentially dangerous optimizations/code
},
output: {
comments: false,
space_colon: false
}
}),
new OptimizeJsPlugin({
sourceMap: false
}),
new webpack.optimize.OccurrenceOrderPlugin()
]
};
const testConfig = {
devtool: 'inline-source-map',
module: {
rules: [
{test: /\.scss$/, loaders: ['raw-loader', 'postcss-loader', 'sass-loader'], exclude: [/\.global\.scss$/, /node_modules/]},
{test: /\.global\.scss$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'], exclude: [/node_modules/]},
{test: /\.css$/, loaders: ['style-loader', 'css-loader'], include: [/node_modules/]},
{test: /\.css$/, loaders: ['to-string-loader', 'css-loader'], exclude: [/node_modules/]},
{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',
name: '../fonts/[name].[ext]',
publicPath: '/fonts/'
}
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
options: {
name: '../fonts/[name].[ext]',
publicPath: '/fonts/'
}
},
{
test: /\.ts$/,
use: [
{
loader: 'awesome-typescript-loader',
query: {
// use inline sourcemaps for "karma-remap-coverage" reporter
sourceMap: false,
inlineSourceMap: true,
compilerOptions: {
// Remove TypeScript helpers to be injected
// below by DefinePlugin
removeComments: true
}
},
},
'angular2-template-loader'
],
exclude: [/\.e2e\.ts$/]
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader',
exclude: [/spec-bundle\.js/, /node_modules/]
},
{
enforce: 'post',
test: /\.(js|ts)$/,
loader: 'istanbul-instrumenter-loader',
exclude: [
/spec-bundle\.js/,
/\.(e2e|spec)\.ts$/,
/node_modules/
]
}
]
}
};
const devConfig = {
devtool: 'cheap-module-source-map',
module: {
loaders: [
{
test: /\.ts$/,
loader: 'tslint-loader',
options: {
configFile: 'tslint.json'
},
exclude: [/\.(spec|e2e)\.ts$/, /node_modules/]
},
]
}
};
switch (process.env.NODE_ENV) {
case 'staging':
case 'production':
module.exports = webpackMerge(commonConfig, prodConfig);
break;
case 'test':
module.exports = webpackMerge(commonConfig, testConfig);
break;
case 'development':
default:
module.exports = webpackMerge(commonConfig, devConfig);
}
And this is my tsconfig.json:
{
"angularCompilerOptions": {
"entryModule": "src/app.module#AppModule",
"genDir": "./ngfactory",
"debug": false
},
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true
},
"buildOnSave": false,
"compileOnSave": false,
"compilerOptions": {
"allowUnusedLabels": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"es6",
"dom"
],
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": false,
"noImplicitReturns": true,
"outDir": "public/js",
"rootDir": ".",
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true,
"target": "ES5",
"typeRoots": [
"node_modules/#types"
],
"types": ["node", "jasmine"]
},
"exclude": [
"node_modules",
"public"
]
}
And so i have this error:
Please help me!!
Thanks

Webpack babel config for both server and client javascript?

I'm trying to figure out how to have a single webpack config file that works for transforming both server (node.js) js and client js with the es2015 preset. Currently I have to specifically set "target: 'node'" for it to correctly process node-based files. If I don't, then webpack does the transformation based on the default "target: 'web'". It then reports errors because the 'mysql' module being imported clearly won't work for web.
How can I unify both into the same config file so that server and client js will be transformed separately? Or do I need separate configs entirely?
Sample webpack.config.js
'use strict';
var path = require('path');
var webpack = require('webpack');
module.exports = {
target: 'node',
resolve: {
root: path.resolve(__dirname),
extensions: ['', '.js']
},
entry: [
'babel-polyfill',
'./index.js',
],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
}
};
Sample js code
import 'babel-polyfill';
import mysql from 'mysql';
class Test {
constructor () {
}
get read () {
}
};
You can pass multiple configs for Webpack to process at the same time. Simply return an array of configuration objects.
export default [
{
// config 1 here
},
{
// config 2 here
},
];
Extra tip: if you use .babel.js as extension for your config file, Webpack will run it through Babel for you, which allows you to use ES6 in your Webpack config.
Bonus: the snippet below
// Source: https://gist.github.com/Ambroos/f23d517a4261e52b4591224b4c8df826
import webpack from 'webpack';
import path from 'path';
import CleanPlugin from 'clean-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import AssetsPlugin from 'assets-webpack-plugin';
import CompressionPlugin from 'compression-webpack-plugin';
import autoprefixer from 'autoprefixer';
import rucksack from 'rucksack-css';
import cssnano from 'cssnano';
import moment from 'moment';
const sharedPlugins = [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /nl/),
new webpack.optimize.AggressiveMergingPlugin({}),
new webpack.optimize.OccurenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({
compress: {
drop_console: true,
screw_ie8: true,
sequences: true,
properties: true,
dead_code: true,
drop_debugger: true,
conditionals: true,
comparisons: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
if_return: true,
join_vars: true,
cascade: true,
negate_iife: true,
hoist_funs: true,
warnings: false,
},
mangle: {
screw_ie8: true,
},
output: {
screw_ie8: true,
preamble: '/* Website - ' + moment().format() + ' */',
},
}),
];
const sharedServerPlugins = [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /nl/),
new webpack.optimize.AggressiveMergingPlugin({}),
new webpack.optimize.OccurenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({
compress: {
drop_console: false,
screw_ie8: true,
sequences: true,
properties: true,
dead_code: true,
drop_debugger: false,
conditionals: true,
comparisons: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
if_return: true,
join_vars: true,
cascade: true,
negate_iife: true,
hoist_funs: true,
warnings: false,
},
mangle: {
screw_ie8: true,
},
output: {
screw_ie8: true,
preamble: '/* Website - ' + moment().format() + ' */',
},
}),
];
const PATHS = {
build: path.resolve(__dirname, '..', 'build'),
sourcemaps: path.resolve(__dirname, '..', 'build', 'sourcemaps'),
browserSource: path.resolve(__dirname, '..', 'src', 'browser', 'index.js'),
browserBuild: path.resolve(__dirname, '..', 'build', 'browser'),
serverSource: path.resolve(__dirname, '..', 'src', 'server', 'index.js'),
serverAssetsSource: path.resolve(__dirname, '..', 'src', 'server', 'assets', 'index.js'),
serverBuild: path.resolve(__dirname, '..', 'build', 'server'),
};
export default [
// Browser
{
entry: { browser: PATHS.browserSource },
output: {
path: PATHS.browserBuild,
filename: 's/[chunkhash].js',
chunkFilename: 's/async-[chunkhash].js',
publicPath: '/',
sourceMapFilename: '../sourcemaps/browser/[file].map',
},
devtool: 'hidden-source-map',
plugins: [
new AssetsPlugin({
prettyPrint: true,
path: path.resolve(PATHS.build, 'browserAssets'),
filename: 'index.js',
processOutput: assets => `module.exports = ${JSON.stringify(assets, null, ' ')};`,
}),
new CleanPlugin([PATHS.browserBuild, PATHS.sourcemaps], path.resolve(PATHS.build, 'browserAssets')),
new ExtractTextPlugin('s/[contenthash].css'),
new CompressionPlugin({
asset: '{file}.gz',
algorithm: 'gzip',
regExp: /\.js$|\.html$|\.css$|\.svg$|\.eot$|\.xml$/,
threshold: 1400,
minRation: 0.8,
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
WEBPACK_ENV: JSON.stringify('browser'),
APP_ENV: (process.env.APP_ENV && JSON.stringify(process.env.APP_ENV)) || undefined,
},
}),
].concat(sharedPlugins),
externals: [
{ browserConfig: 'var websiteBrowserConfig' },
{ programs: 'var programs' },
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
},
{
test: /\.json$/,
loader: 'json',
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract(
'style',
[
'css?importLoaders=2&localIdentName=css-module-[hash:base64]',
'postcss',
'sass',
]
),
},
{
test: /\.(gif|png|jpe?g|svg|ico)$/i,
loaders: [
'url?limit=1400&name=s/i/[sha512:hash:base64:16].[ext]',
'image-webpack?bypassOnDebug',
],
},
{
test: /isotope\-|fizzy\-ui\-utils|desandro\-|masonry|outlayer|get\-size|doc\-ready|eventie|eventemitter/,
loader: 'imports?define=>false&this=>window',
},
{
test: /flickity/,
loader: 'imports?define=>false&this=>window',
},
{
test: /node_modules\/unipointer/,
loader: 'imports?define=>undefined',
},
],
},
postcss: () => {
return [rucksack, autoprefixer, cssnano];
},
},
// Server assets
{
entry: { assets: PATHS.serverAssetsSource },
target: 'node',
output: {
path: PATHS.browserBuild,
libraryTarget: 'commonjs',
filename: '../serverAssets/index.js',
publicPath: '/',
},
plugins: [
// assetsWriter,
new CompressionPlugin({
asset: '{file}.gz',
algorithm: 'gzip',
regExp: /\.js$|\.html$|\.css$|\.svg$|\.eot$|\.xml$/,
threshold: 1400,
minRation: 0.8,
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
WEBPACK_ENV: JSON.stringify('assets'),
APP_ENV: (process.env.APP_ENV && JSON.stringify(process.env.APP_ENV)) || undefined,
},
}),
].concat(sharedPlugins),
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
},
{
test: /\.json$/,
loader: 'json',
},
{
test: /\.(gif|png|jpe?g|svg|ico)$/i,
loaders: [
'url?limit=1400&name=s/i/[sha512:hash:base64:16].[ext]',
'image-webpack?bypassOnDebug',
],
},
],
},
},
// Server
{
entry: PATHS.serverSource,
target: 'node',
output: {
path: PATHS.build,
libraryTarget: 'commonjs',
filename: 'server/server.js',
publicPath: '/s/',
sourceMapFilename: 'sourcemaps/browser/[file].map',
},
externals: [
{ serverAssets: '../serverAssets/index.js' },
{ browserAssets: '../browserAssets/index.js' },
{ vrtConfig: '../../env_vars.js' },
/^(?!\.|\/).+/i,
/webpack-assets\.json/,
],
plugins: [
new CleanPlugin(PATHS.serverBuild),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
WEBPACK_ENV: JSON.stringify('server'),
APP_ENV: (process.env.APP_ENV && JSON.stringify(process.env.APP_ENV)) || undefined,
},
}),
].concat(sharedServerPlugins),
node: {
__dirname: false,
__filename: false,
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
},
{
test: /\.json$/,
loader: 'json',
},
],
},
},
];
That is the config we use in one of our sites with a partially shared codebase, and partially shared assets. It consists of three Webpack builds in one:
Browser
Server assets (images/fonts/... that will be referenced in server-generated HTML)
Server code (Node)
The server code has a few special properties:
target: 'node' (Webpack needs this)
output.libraryTarget: 'commonjs' (makes Webpack use commonjs for unbundled libs)
externals: [ /^(?!\.|\/).+/i, ] (makes Webpack not bundle anything in node_modules, or anything that is not a relative path (starting with . or /)
This combination makes Webpack only process your own code, and access other modules and libraries through require. Which means your dependencies using native bindings won't break as they won't be bundled.

webpack dev server does not show the content

I have the following problem when running the webpack dev server:
when I run npm start, it show the following:
➜ directory git:(staging) ✗ npm start
directory #1.0.0 start directory
BUILD_DEV=1 BUILD_STAGING=1 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/
webpack result is served from /undefined/
content is served from
directory
404s will fallback to /index.html
Hash: 75773622412153d5f921
Version: webpack 1.12.11
Time: 43330ms
I guess the problem might because the following line:
webpack result is served from /undefined/
When I open the browser at http://localhost:8080/, it appear as follow:
Cannot GET /
and there is no thing in the console.
Do you have any ideas for this problem ?
UPDATE: WEBPACK CONFIG FILE
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const deps = [
'moment/min/moment.min.js',
'underscore/underscore-min.js',
];
/* Include SASS path here if you want to this in your sass files:
* #import 'bourbon';
*/
const bourbon = require('node-bourbon').includePaths;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const SASS_DEPS = [bourbon].toString();
const BUILD_NUMBER = process.env.CI_BUILD_NUMBER;
const common = {
entry: path.resolve(ROOT_PATH, 'app/index.js'),
output: {
filename: BUILD_NUMBER + '-[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: `/${BUILD_NUMBER}/`,
},
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass?includePaths[]=' + SASS_DEPS],
include: path.resolve(ROOT_PATH, 'app'),
},
{
test: /\.css$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass?includePaths[]=' + SASS_DEPS,
'postcss'
],
include: path.resolve(ROOT_PATH),
exclude: /(pure\/grids|Grids).*\.css$/,
},
{
test: /(pure\/grids|Grids).*\.css$/,
loaders: [
'style',
'css',
'sass?includePaths[]=' + SASS_DEPS,
],
include: path.resolve(ROOT_PATH),
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff',
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
},
{
test: /\.json$/,
loader: 'json',
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: path.resolve(ROOT_PATH, 'app/index.html'),
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true,
},
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')),
__STAGING__: JSON.stringify(JSON.parse(process.env.BUILD_STAGING || 'false')),
__API_HOST__: JSON.stringify(process.env.BUILD_STAGING ? 'my.api' : 'my.api'),
}),
],
resolve: {
alias: {
'styles': path.resolve(ROOT_PATH, 'app/styles'),
},
extensions: ['', '.js', '.jsx', '.json'],
},
postcss: function() {
return [
require('postcss-import'),
require('autoprefixer'),
require('postcss-cssnext'),
]
}
};
if (TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
output: {
filename: '[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: '/',
},
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'react-hot',
'babel-loader'
],
include: path.resolve(ROOT_PATH, 'app'),
},
],
},
devServer: {
colors: true,
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
});
} else if (TARGET === 'build' || TARGET === 'builds') {
const config = {
resolve: {
alias: {},
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.resolve(ROOT_PATH, 'app'),
},
],
noParse: [],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
screw_ie8: true,
warnings: false,
},
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
}),
],
};
deps.forEach((dep) => {
const depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
module.exports = merge(common, config);
}
Same problem occurred to me when i started using babel-loader > 6.
It was fixed by adding contentBase in webpack dev server configuration.
In my case it looked like this
new WebPackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
contentBase: __dirname + '/public'
}).listen(3000, 'localhost')
I would be great to see your webpack config file to pin point the exact problem, but from the error message, there could be multiple problem
Make sure you are on the right port
Make sure your webpack config has
path and public path setup
Make sure you have contentBase setup as
well
Without seeing your webpack file and more concrete detail, it is quite hard to pinpoint the issue. But you can always go to https://webpack.github.io/docs/webpack-dev-server.html for information on how to set it up.

Categories

Resources