I am trying to configure webpack 2 for my react development app. Seems like there is something I am missing below is my webpack.config.dev
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var loaders = [
{
loader: 'css-loader',
options: {
modules: true
}
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
];
export default {
resolve: {
extensions: ['', '.js', '.jsx', '.json']
},
devtool: 'eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
entry: {
app: path.resolve(__dirname, 'src/index.js'),
vendor: ["react", "react-dom"]
},
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
path: path.resolve(__dirname, 'dist'), // Note: Physical src are only output by the production build task `npm run build`.
publicPath: '/',
filename: "[name].entry.chunk.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: '[name].[hash].js', }),
new ExtractTextPlugin("[name].css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'), // Tells React to build in either dev or prod modes. https://facebook.github.io/react/downloads.html (See bottom)
__DEV__: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({ // Create HTML file that includes references to bundled CSS and JS.
template: path.join(__dirname, './src/index.html'),
filename: 'index.html',
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true
},
})
],
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel']},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
{test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
{test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: loaders,
}) },
{test: /\.json$/, loader: "json"}
]
},
};
This is my github repo https://github.com/sourabh-garg/Webpack-2-starter-kit please clone it and and run npm install followed by npm start.
When I run it I get
ERROR in ./src/index.js
Module build failed: SyntaxError: Unexpected token (6:0)
render(
"<h1>Hello World!</h1>", document.getElementById('app')
);
Please let me know what I am missing.
Related
I have a small React app that I'm minifying with Webpack, and I noticed that ~80% of my minified index.js file is just Bootstrap css that I'm not using, plus Webpack warns me that my entry file is too big (~900kb vs ~250kb recommended). I found a few answers here from a long time ago that said to remove parts of bootstrap.min.css file that I don't need, and I'm wondering if that's still the recommended solution for a React app using react-bootstrap?
This is my production webpack config:
const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
module.exports = {
entry: '/src/index.tsx',
output: {
path: path.resolve(__dirname, 'prod'),
},
mode: 'production',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
},
{
test: /\.css$/,
include: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules/react-toastify/dist'),
path.resolve(
__dirname,
'node_modules/bootstrap/dist/css/bootstrap.min.css'
),
path.resolve(
__dirname,
'node_modules/react-grid-layout/css/styles.css'
),
path.resolve(
__dirname,
'node_modules/react-resizable/css/styles.css'
),
],
use: ['style-loader', 'css-loader'],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: 'ts-loader',
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
}),
new FaviconsWebpackPlugin('./src/logo.png'),
],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
}
And at the top of my App.tsx file I have
import 'bootstrap/dist/css/bootstrap.min.css'
Ok so I was able to (I think) accomplish what I was asking. I first tried to follow the instructions here:
https://medium.com/dwarves-foundation/remove-unused-css-styles-from-bootstrap-using-purgecss-88395a2c5772
So running purgecss --css [path to bootstrap css] ---content src/index.html --output public did create very minified CSS files, but either I did something wrong or purgecss removed too much, because the bootstrap styles didn't seem to be applied to anything.
Instead, I installed MiniCssExtractPlugin, and pointed webpack to the full bootstrap.min.css file. Running webpack with the below (updated) webpack.prod.js config file reduced the entry file size from ~900kb to ~360kb, which is still above the recommended limit but is about 1/3 the size of the entry before these changes.
Edit: and it also seems good that now the css styles are in their own actual main.css file, rather than for some reason being inside main.js, which is how it was before adding MiniCssExtractPlugin.
const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: '/src/index.tsx',
output: {
path: path.resolve(__dirname, 'prod'),
},
mode: 'production',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
},
{
test: /\.css$/,
include: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'public')
],
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: 'ts-loader',
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
}),
new MiniCssExtractPlugin({filename: "[name].css", chunkFilename: "[id].css"}),
new FaviconsWebpackPlugin('./src/logo.png'),
],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
}
I have this configuration in my webpack and I need to add sass-loader,
I already added the dependencies using
npm install sass-loader sass webpack --save-dev
But I'm confused where I include the sass loader and the documentation settings.
Now how to add to my webpack?
'use strict'
const path = require('path')
const webpack = require('webpack')
const validate = require('webpack-validator')
module.exports = validate({
devtool: 'source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
path.join(__dirname, 'src', 'index'),
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
preLoaders: [{
test: /\.js$/,
exclude: /node_modules/,
include: /src/,
loader: 'standard'
}],
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
include: /src/,
loader: 'babel'
}],
}
})
I assume you want to add sass-loader in order to support scss files.
Add a new item to the loaders/rules array:
If you use webpack < v3:
loaders:[
...,
{
test: /\.(scss|sass)$/,
loader: 'style-loader!css-loader!sass-loader'
}
]
For webpack > v3 add a rule like this:
rules:[
...,
{
test: /\.(scss|sass)$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
}
]
For more details look here https://webpack.js.org/loaders/sass-loader/
I would like to use react-force-graph in my app, but I am getting an error Uncaught TypeError: selection.interrupt is not a function. The error comes from zoom.js which is dependency of react-forrce-graph package.
I found that the problem could be solved by downgrading the d3-selection package from version 1.3.2 to version 1.3.0. How to do it? I am able to co id by changing version dependency in package.json in react-force-graph package, bud after updating packages the change will be lost.
I also found, the problem could be caused by webpack setting, but I it is all i know...
I found, similar problem in different package and they solved this by downgrading d3 package version and load via yarn instead of npm.
It is weird, because their demo working properly, so is there any problem in my webpack settings? Or is there any problem in npm?
Complete error from console:
*Uncaught TypeError: selection.interrupt is not a function
at Function../node_modules/force-graph/node_modules/d3-
zoom/src/zoom.js.webpack_exports.default.zoom.transform (zoom.js:90)
at Function../node_modules/force-graph/node_modules/d3-
zoom/src/zoom.js.webpack_exports.default.zoom.translateBy (zoom.js:119)
at adjustCanvasSize (force-graph.module.js:605)
at Function.init (force-graph.module.js:852)
at u (kapsule.min.js:1)
at Object.r [as comp] (kapsule.min.js:1)
at FromKapsuleComp.componentDidMount (react-kapsule.module.js:85)
at commitLifeCycles (react-dom.development.js:14685)
at commitAllLifeCycles (react-dom.development.js:15905)
at HTMLUnknownElement.callCallback (react-dom.development.js:145)*
webpack.conf.dev.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
module.exports = {
mode : 'development',
devtool: 'inline-source-map',
entry: {
app: ['./src/index', 'webpack-hot-middleware/client?reload=true']
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
historyApiFallback: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
//new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
inject: 'body',
title: 'Hot Module Reload'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
}),
new FaviconsWebpackPlugin({
// Your source logo
logo: './src/img/ikona.png',
// The prefix for all image files (might be a folder or a name)
prefix: 'favicon-[hash]/',
// Emit all stats of the generated icons
emitStats: false,
// don't rebuild the favicons until those hashes change
persistentCache: true,
// Inject the html into the html-webpack-plugin
inject: true,
// favicon background color (see https://github.com/haydenbleasel/favicons#usage)
background: '#EE3C96',
// favicon app title (see https://github.com/haydenbleasel/favicons#usage)
//title: 'Bonobox',
// which icons should be generated (see https://github.com/haydenbleasel/favicons#usage)
icons: {
android: false,
appleIcon: false,
appleStartup: false,
coast: false,
favicons: true,
firefox: false,
opengraph: false,
twitter: false,
yandex: false,
windows: false
}
})
],
module: {
rules: [
{
test: /\.js$/,
loaders: ['babel-loader'],
include: path.join(__dirname, 'src')
},
{
test: /\.html$/,
loaders: ['html-loader'],
},
{
test: /\.scss$/,
use: [
{loader: "style-loader"},
{loader: "css-loader"},
{loader: "sass-loader"}
]
},
{
test: /\.less$/,
use: [
{loader: "style-loader"},
{loader: "css-loader"},
{loader: "less-loader"}
]
},
{
test: /\.css$/,
use: [
{loader: "style-loader"},
{loader: "css-loader"}
]
},
{
test: /\.json$/,
loader: 'json-loader'
},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=image/svg+xml'},
{test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/font-woff"},
{test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/font-woff"},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/octet-stream"},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader"},
{test: /\.(png|jpg|gif|mp4)$/, loader: 'file-loader?limit=8192'}
]
}
};
npm version: newest - yesterday updated (error before and also after update)
EDIT: yarn - same problem
I tried to add 'target:node' to the webpack.dev.js to exclude node_modules from my bundle file. This results in an error. Now I have 'target:web' but has the node_modules back in. This is my config file for the applicationpart(trying to use DllReferencePlugin):
var path = require("path");
var webpack = require("webpack");
module.exports = {
target:'web',
devServer: {
contentBase: path.join(__dirname, "build"),
compress: true,
port: 9000
},
node: {
fs: 'empty'
},
cache: true,
devtool: "eval", //or cheap-module-eval-source-map
entry: {
app: path.join(__dirname, "client/app", "app.js")
},
output: {
path: path.join(__dirname, "buildf"),
filename: "ha.js",
chunkFilename: "[name].js"
},
plugins: [
//Typically you'd have plenty of other plugins here as well
new webpack.DllReferencePlugin({
context: path.join(__dirname, "client"),
manifest: require("./build/vendor-manifest.json")
}),
],
module: {
loaders: [
{
test: /\.js?$/,
loader: "babel-loader",
include: [
path.join(__dirname, "client") //important for performance!
],
exclude: [
path.resolve(__dirname, "node_modules")
],
query: {
cacheDirectory: true, //important for performance
plugins: ["transform-regenerator"],
presets: ["es2015", "stage-0"]
}
},
{ test: /\.(scss|sass)$/, loader: ['style-loader', 'css-loader', 'sass-loader'] },
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.css$/, loader: 'css-loader' }
]
}
};
How can I exclude the node_modules folder from the ha.js (app bundle) build? for the complete code see here
Here an example:
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/, // <---
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
I use webpack HotModuleReplacementPlugin to let my website could hot reload when I fix the code.
But I don't know how to build two html page.
I want to build two page "index.html" & "introduction.html"
Now I use these code in my webpack.config.js but it will have a problem, in the Chrome dev tool would show
「Uncaught Error: _registerComponent(...): Target container is not a DOM element.」
How could I solved these problem?
var webpack = require('webpack');
var path = require('path');
var htmlWebpackPlugin = require('html-webpack-plugin');
var autoprefixer = require('autoprefixer');
var config = {
entry: {
index: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'src/index.jsx')
],
introduction: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'src/introduction.jsx')
],
},
output: {
path: path.resolve(__dirname, 'build'),
publishPath: '/',
filename: 'js/[name].js'
},
module: {
loaders: [
{
test:/\.jsx?$/,
exclude: /node_modules/,
loader: 'react-hot!babel'
},
{
test: /\.sass$/,
execlude: /node_modules/,
loader: 'style!css!postcss!sass'
},{
test: /\.scss$/,
execulde: /node_modules/,
loader: 'style!css!postcss!sass'
},
{
test: /\.css$/,
exclude: /node_modules/,
loader: 'style!css!postcss',
},
{
test: /\.(jpg|png|gif)$/,
exclude: /node_modules/,
loader: 'file?name=images/[name].[ext]'
},
{
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'
}
]
},
postcss: [
autoprefixer({ browsers: ['last 2 versions']})
],
resolve: {
extensions: ['', '.js', '.jsx']
},
exclude: [
/(test)/
],
devServer: {
contenBase: './dist'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new htmlWebpackPlugin({
filename: 'index.html',
template: './src/html/index.html'
}),
new htmlWebpackPlugin({
filename: 'introduction.html',
template: './src/html/introduction.html'
}),
]
}
module.exports = config;