I was trying to use react-datetime-range-picker and When I import it I started getting error.
I have tried other solution but did not work.
Full Error
javascript modules 6.14 KiB
./src/pages/Campaign/CampaignNew.js 2.39 KiB [built]
./node_modules/react-datetime-range-picker/dist/style.css 3.75 KiB [built] [1 error]
ERROR in ./node_modules/react-datetime-range-picker/dist/style.css 5:0
Module parse failed: Unexpected token (5:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured
to process this file. See https://webpack.js.org/concepts#loaders
| */
|
> .rdt {
| position: relative;
| }
# ./node_modules/react-datetime-range-picker/dist/index.js 27:0-22
# ./src/pages/Campaign/CampaignNew.js 3:0-62
# ./src/App.js 6:0-55 16:46-57
# ./src/index.js 1:0-24
I checked webpack.config.js but it looks correct to me.
I have installed style-loader, css-loader
webpack.config.js
const path = require("path");
const webpack = require("webpack");
require('dotenv').config({path: './.env'});
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./static/app_chat/js"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.(jsx|js)$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.(sass|scss|css)$/,
exclude: /node_modules/,
use: ["style-loader", "css-loader"],
},
],
},
optimization: {
minimize: true,
},
plugins: [
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env),
}),
],
};
package.json
{
"name": "app_chat",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.20.12",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"axios": "^1.2.4",
"babel-loader": "^9.1.2",
"dotenv": "^16.0.3",
"react": "^18.2.0",
"react-datetime": "^3.2.0",
"react-datetime-range-picker": "^3.0.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.7.0",
"react-switch": "^7.0.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
},
"devDependencies": {
"css-loader": "^6.7.3",
"style-loader": "^3.3.1"
}
}
What should I do to fix this problem ?
Please try the following steps if you want to have setup for development and production: (SCSS)
Install the following packages:
yarn add -D postcss-loader postcss-flexbugs-fixes postcss-preset-env style-loader mini-css-extract-plugin
postcss-normalize resolve-url-loader sass-loader
Update your webpack config as follows:
{
test: /\.s?[ac]ss$/,
//removed (exclude: /node_modules/) to enable using external styles
use: [
{
// style-loader => insert styles in the head of the HTML as style tags or in blob links
// MiniCssExtractPlugin => extract styles to a file
loader: isDevelopment ? 'style-loader' : MiniCssExtractPlugin.loader,
//if source map is set to true from previous loaders => this loader will be true as well
},
{
//Resolves #import statements
loader: 'css-loader',
options: {
// used for debugging the app (to see from which component styles are applied)
sourceMap: isDevelopment,
// Number of loaders applied before CSS loader (which is postcss-loader)
importLoaders: 3,
// the following is used to enable CSS modules
...(isCssModules
? {
modules: {
//exclude external styles from css modules transformation
auto: (resourcePath) => !resourcePath.includes('node_modules'),
mode: (resourcePath) => {
if (/global.scss$/i.test(resourcePath)) {
return 'global';
}
return 'local';
},
localIdentName: isDevelopment ? '[name]_[local]' : '[contenthash:base64]',
localIdentContext: srcPath,
localIdentHashSalt: 'react-boilerplate',
exportLocalsConvention: 'camelCaseOnly',
},
}
: {}),
},
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
ident: 'postcss',
plugins: [
'postcss-flexbugs-fixes',
postcssPresetEnv({
stage: 3,
//uncomment the following if you want to prefix grid properties
// autoprefixer: { grid: true },
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
'postcss-normalize',
],
},
sourceMap: isDevelopment,
},
},
{
//Rewrites relative paths in url() statements based on the original source file
loader: 'resolve-url-loader',
options: {
//needs sourcemaps to resolve urls (images)
sourceMap: true,
},
},
{
//Compiles Sass to CSS
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
Check out the following repository for reference:
React webpack boilerplate
Related
I'm currently in the process of learning React and have encountered an error in the webpack section. I use the plugin transform-class-properties for the arrow functions but webpack shows error in processing them.
ERROR in ./src/app.js 86:20
Module parse failed: Unexpected token (86:20)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| }
| }
> handleRemoveAll = () => {
| this.setState( () => ({ options: [] }));
| }
error Command failed with exit code 2.
my webpack config file looks like this
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
};
and this is my package.json
{
"name": "indecision-app",
"version": "1.0.0",
"main": "index.js",
"author": "Test User",
"license": "MIT",
"scripts": {
"serve": "live-server public/",
"build": "webpack",
"build-babel": "babel src/app.js --out-file=public/scripts/app.js --presets=react,env --plugins=transform-class-properties --watch"
},
"dependencies": {
"babel-cli": "^6.26.0",
"babel-loader": "^8.1.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"live-server": "^1.2.1",
"webpack": "^4.44.0"
},
"devDependencies": {
"webpack-cli": "^3.3.12"
}
}
You should add a loader to webpack configuration
https://survivejs.com/webpack/loading/javascript/
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
Also a .babelrc file
{
presets: [
[
'#babel/preset-env',
{
targets: {
browsers: 'last 2 versions',
},
loose: true,
modules: false,
},
],
'#babel/preset-react',
],
plugins: ['transform-class-properties'],
}
I have a complete site that I want to design a build tool for it.In fact, I chose Webpack for doing that. The project structure is like this:
I have nunjucks, html, css, sass and js files. I must bundle them via webpack. My webpack config file is here:
var HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const NunjucksWebpackPlugin = require('nunjucks-webpack-plugin')
module.exports = {
entry: ['./src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
writeToDisk: true
},
plugins: [
new CopyPlugin([
{ from: 'public/images', to: 'images' },
{ from: 'public/fonts', to: 'fonts' },
{ from: 'src/pages/about', to: '.' }
]),
new CleanWebpackPlugin(),
// new HtmlWebpackPlugin()
new HtmlWebpackPlugin({
title: 'Asset Management' //title of file.html
})
],
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
},
{
test: /\.(njk|nunjucks)$/,
loader: 'nunjucks-loader'
},
{
// to auto refresh index.html and other html
test: /\.html$/,
loader: 'raw-loader',
exclude: /node_modules/
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: {
interpolate: true
}
}
]
}
]
}
}
The "index.js" file also is like this:
import _ from 'lodash'
import './pages/about/about_moon.scss'
import './pages/about/about_moon.html'
var tpl = require('./pages/home/index_moon.njk')
var html = tpl.render({ message: 'Foo that!' })
function component() {
return element
}
document.body.appendChild(component())
I configured the "package.json" file and defined scripts to run webpack:
"start": "webpack-dev-server --open",
"build": "webpack"
The problem is when I run npm run build, the dist folder was made and it had a html file but there is nothing to show. I have already had some html files and wanted to bundle all of them to "bundle.js", but I have not known how. Would you please tell me how I can bundle this project?
Thank you in advance.
Problem solved. I changed the Webpack.config.js file to this:
const path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
module.exports = {
entry: ['./src/index.js', './script.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
// HtmlWebpackPluginConfig
new HtmlWebpackPlugin({
filename: 'index.html',
inject: 'head',
template: './index.njk'
}),
new CleanWebpackPlugin(),
new CopyPlugin([
{ from: 'public/images', to: 'images' },
{ from: 'public/fonts', to: 'fonts' }
])
],
module: {
rules: [
{
test: /\.exec\.js$/,
use: ['script-loader']
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.(scss)$/,
use: [
{
// Adds CSS to the DOM by injecting a `<style>` tag
loader: 'style-loader'
},
{
// Interprets `#import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')]
}
}
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader'
}
]
},
{
// HTML LOADER
// Super important: We need to test for the html
// as well as the nunjucks files
test: /\.html$|njk|nunjucks/,
use: [
'html-loader',
{
loader: 'nunjucks-html-loader',
options: {
// Other super important. This will be the base
// directory in which webpack is going to find
// the layout and any other file index.njk is calling.
// searchPaths: [...returnEntries('./src/pages/**/')]
// Use the one below if you want to use a single path.
// searchPaths: ['./']
}
}
]
}
]
}
}
Also, I wrote the script.js file like this, since, function names were changed and they could not be run after bundling.
document.getElementById('body').onload = function() {
console.log('Document loaded')
var menu = localStorage.getItem('menu')
if (menu === 'opened')
document.getElementById('navigation').classList.add('opened')
}
document.getElementById('menu-button').onclick = function() {
// localstorage used to define global variable
var menu = localStorage.getItem('menu')
localStorage.setItem('menu', menu === 'closed' ? 'opened' : 'closed')
document.getElementById('navigation').classList.toggle('opened')
}
// Window.onLoad = onLoad // global variable in js
The index.js was used to import other files and it was like this:
import _ from 'lodash'
require('../index.njk')
require('../base.html')
require('../style.css')
This is the Json file:
{
"name": "menu_moon",
"version": "1.0.0",
"description": "",
"private": true,
"dependencies": {
"browser-sync": "^2.26.7",
"extract-text-webpack-plugin": "^3.0.2",
"fast-glob": "^3.1.1",
"fs-extra": "^8.1.0",
"g": "^2.0.1",
"html-loader": "^0.5.5",
"i": "^0.3.6",
"lodash": "^4.17.15",
"mkdirp": "^0.5.1",
"nunjucks": "^3.2.0",
"nunjucks-html-loader": "^1.1.0",
"nunjucks-isomorphic-loader": "^2.0.2",
"nunjucks-loader": "^3.0.0",
"raw-loader": "^4.0.0"
},
"devDependencies": {
"browser-sync-webpack-plugin": "^2.2.2",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.5",
"css-loader": "^3.2.1",
"file-loader": "^5.0.2",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.13.0",
"nunjucks-webpack-plugin": "^5.0.0",
"sass-loader": "^8.0.0",
"script-loader": "^0.7.2",
"style-loader": "^1.0.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"scripts": {
"moon-start": "browser-sync start --server --files './**/*.*'",
"moon-build": "node build_product_moon.js",
"start": "webpack-dev-server --open",
"build": "webpack"
},
"author": "",
"license": "ISC"
}
I hope it was useful for others.
I'm facing a problem with webpack. My project has the following structure.
Folder structure:
src
js
app.js // For importing app.scss file
vendor.js // For importing vendor.scss file
scss
app.scss // Our custom styles
vendor.scss // Require all vendor styles from node_modules
package.json
postcss.config.js
webpack.config.js
Inside scss folder there are 2 files app.scss & vendor.scss. app.scss file contains all our custom styles, vendor.scss file contains all vendor styles such as bootstrap library styles.
After webpack command:
npm run dev
Webpack import these scss files through JavaScript files and add vendor prefixes via postcss-loader and output on a dist
folder.
But I don't want to add vendor prefixes on vendor.scss file because the vendor library already has vendor prefixes. So is there a way to exclude vendor.scss file from postcss-loader.
Full Code:
src/js/app.js:
import '../scss/app.scss'
src/js/vendor.js:
import '../scss/vendor.scss'
src/scss/app.scss:
// Our custom styles
.app {
display: flex;
}
src/scss/vendor.scss:
// Vendor Styles
.container {
display: flex;
}
#import '~bootstrap/scss/bootstrap';
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode development --progress true --colors"
},
"author": "",
"license": "MIT",
"dependencies": {
"bootstrap": "^4.2.1"
},
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.3.1",
"autoprefixer": "^9.4.6",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.0",
"filemanager-webpack-plugin": "^2.0.5",
"mini-css-extract-plugin": "^0.5.0",
"node-sass": "^4.11.0",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1"
}
}
postcss.config.js:
module.exports={
plugins: [
require('autoprefixer')({
'browsers': [
'>= 1%',
'last 1 major version',
'not dead',
'Chrome >= 45',
'Firefox >= 38',
'Edge >= 12',
'Explorer >= 10',
'iOS >= 9',
'Safari >= 9',
'Android >= 4.4',
'Opera >= 30'
],
cascade: true
})
]
};
webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
module.exports = function() {
return ({
entry: {
'vendor': './src/js/vendor.js',
'app': './src/js/app.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].[chunkhash].js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
}, {
loader: 'css-loader',
}, // translates CSS into CommonJS
{
loader: 'postcss-loader',
}, // Add vendor prefixes on build css file
{
loader: 'sass-loader',
} // compiles Sass to CSS
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css'
}),
// Before Build
new FileManagerPlugin({
onStart: {
delete: [
'dist',
],
}
}),
]
});
};
Zip file.
So you want vendor prefixes don't add on Webpack generated vendor.css file.
Remember Webpack parse loader array on reverse order. You could add exclude property on the object of postcss-loader with the regular expression.
webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
module.exports = function() {
return ({
entry: {
'vendor': './src/js/vendor.js',
'app': './src/js/app.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].[chunkhash].js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.s(c|a)ss$/,
use: {
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
},// Take scss file and split into a separate css file
},
{
test: /\.s(c|a)ss$/,
use: {
loader: 'css-loader',
},// Interprets scss #import and url() like import/require()
},
{
test: /\.s(c|a)ss$/,
exclude: [/vendor/],
use: {
loader: 'postcss-loader',
},
}, // PostCSS turns your SCSS file into a JS object & converts that object back to a SCSS file
{
test: /\.s(c|a)ss$/,
use: {
loader: 'sass-loader',
},// look for scss file through sass-loader, compile scss into css code
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css'
}),
// Before Build
new FileManagerPlugin({
onStart: {
delete: [
'dist',
],
}
}),
]
});
};
The case is to have main folder 'Projects' and installed there all webpack 4 files with configs. Inside the 'Projects' folder are many folders like 'Project1', 'Project2', etc...I want to start from 'node_modules' entry point where webpack.config.js is and customize there further entry points like ./Project1/js/app.jsx, outputs like ./Project1/dist/js/main.js, same with scss and index.html, all generated in 'dist' folder. The thing is to have always only once installed node_modules in main 'Projects' folder.
the package.json:
{
"name": "webpack4_example",
"version": "1.0.0",
"main": "index.js",
"browserslist": ["last 2 versions"],
"scripts": {
"build": "webpack --mode production",
"watch": "webpack --watch --mode development",
"start": "webpack-dev-server --open --mode development"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.11",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.0",
"node-sass": "^4.9.0",
"postcss-loader": "^2.1.5",
"prop-types": "^15.6.1",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"sass-loader": "^7.0.1",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4"
}
}
webpack.config.js:
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './Project1/js/app.jsx', // customized entry point
output: {
path: path.resolve(__dirname, 'dist'),
filename: './js/out.js' // generated ./Project1/dist/js/out.js
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
},
{
test: /\.(png|jpe?g)/i,
use: [
{
loader: 'url-loader',
options: {
name: './img/[name].[ext]',
limit: 10000
}
},
{
loader: 'img-loader'
}
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: './Project1/index.html', // not sure how to set these sections
filename: 'index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
})
]
};
.babelrc:
{
"presets": ["env", "react", "stage-2"]
}
From what I understand without customized entry points webpack as default will search for 'Projects/src/...' for all files like scss, js, img, index.html, index.js to operate on them and will generate the 'Projects/dist' folder with all files generated.
The configuration form above compiles without errors but doesn't generate the 'dist' folder anywhere so I'm not sure the compile process is done properly anyway.
Would appreciate any suggestions and solutions
SOLUTION (updated: added working watching files):
ok, I've managed to get it work (starting point is where node_modules and other webpack4 config files are installed, here in Projects main folder)
Projects
|__Project1
| |__js
| | |__app.jsx
| |__dist //desirable result, generated dist folder
| | |__* //all generated folders/files html, js, css, img
| |__index.ejs //renamed from index.html
|
|__Project2 //etc, project folders
|
|__src // if without customized entry points it's default source
| |__folders like /_scss, /img, /js
| |__index.js
| |__index.ejs //renamed index.html, used when no customized
| //entry points are set, same as for all /src
|
|__node_modules
|__.babelrc
|__package.json
|__webpack.config.js
.babelrc
unchanged and same as above in previous post
in this example in Projects folder normally is created src folder with all files/folders to pass thru webpack4, in /src/index.js file must be present, it's for importing some other files
example of index.js
import style from "./_scss/main.scss"; //paths for Projects/src/...
import style from "./main.css";
package.json
{
"name": "webpack4_example",
"version": "1.0.0",
"main": "index.js", // the file explained just above
"browserslist": ["last 2 versions"],
"scripts": {
"dev": "webpack --mode development ./Project1/js/app.jsx --output ./Project1/dist/js/main.js",
"build": "webpack --mode production ./Project1/js/app.jsx --output ./Project1/dist/js/main.js",
"watch": "webpack --watch --mode development",
"start": "webpack-dev-server --mode development --open --watch-content-base ./Project1/js/app.jsx" //watching desired files changes live in browser
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.11",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.0",
"node-sass": "^4.9.0",
"postcss-loader": "^2.1.5",
"prop-types": "^15.6.1",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"sass-loader": "^7.0.1",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4"
}
}
where --mode production | developement | none means formatting optimizations for the output files in dist folder or none of such optimizations, for readibility use none
webpack.config.js
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.(js$|jsx$)/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
},
{
test: /\.(png|jpe?g)/i,
use: [
{
loader: 'url-loader',
options: {
name: './img/[name].[ext]',
limit: 10000
}
},
{
loader: 'img-loader'
}
]
},
{
test: /\.(css$|scss$)/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: './Project1/index.ejs', // entry point for html
filename: 'index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
})
],
watchOptions: { //added to make possible watch files
ignored: /node_modules/,
aggregateTimeout: 300,
poll: 1000
}
};
the customized entry point for index.html where .html extension is changed to .ejs as for working around some issues caused between html-loader and html-webpack-plugin. With .ejs the output html, also placed in dist folder automatically, isn't optimized with formatting and is readible. Watch out if html.ejs contains tag with pinned path for [out].js file (here the one generated in dist folder). The generated index.html from dist folder will add another such line so it will be doubled -> line to delete.
for run use: npm run build, npm start
I have webpack.config.js file and added loader for each font type in individual module block but when I run yarn start
webback complied successfully with this details in terminal
f4769f9bdb7466be65088239c12046d1.eot 20.1 kB [emitted]
448c34a56d699c29117adc64c43affeb.woff2 18 kB [emitted]
fa2772327f55d8198301fdb8bcfc8158.woff 23.4 kB [emitted]
e18bbf611f2a2e43afc071aa2f4e1512.ttf 45.4 kB [emitted]
89889688147bd7575d6327160d64e760.svg 109 kB [emitted]
bundle.js 1.56 MB 0 [emitted] [big] main
favicon.ico 1.15 kB [emitted]
index.html 605 bytes [emitted]
and page open in the browser with bootstrap css applied on it BUT in the console, it gives multiple errors for woff woff2 and ttf file ( see image)
Module parse failed: Unexpected character '' (1:4)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
package.json
"dependencies": {
"bootstrap": "^3.3.7",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.5",
"history": "^4.7.2",
"html-webpack-plugin": "^2.30.1",
"less": "^2.7.3",
"less-loader": "^4.0.5",
"path": "^0.12.7",
"postcss-loader": "^2.0.8",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^5.0.6",
"react-redux-form": "^1.16.0",
"react-router-dom": "^4.2.2",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0",
"style-loader": "^0.19.0",
"svg-inline-loader": "^0.8.0",
"uglifyjs-webpack-plugin": "^1.0.1",
"url-loader": "^0.6.2",
"webpack-combine-loaders": "^2.0.3"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.2",
"babel-loader": "^7.1.2",
"babel-plugin-transform-es2015-destructuring": "^6.23.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"eslint": "^4.10.0",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-flowtype": "^2.39.1",
"eslint-plugin-html": "^3.2.2",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.4.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server"
}
webpack.config.js
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // eslint-disable-line
const path = require('path');
const combineLoaders = require('webpack-combine-loaders');
const BUILD_DIR = path.resolve(__dirname, 'build');
const APP_DIR = path.resolve(__dirname, 'src');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
favicon: './src/assets/favicon.ico',
inject: 'body'
});
// const extractPluginConfig = new ExtractTextPlugin({filename:'style.css', disable: false, allChunks: true});
module.exports = {
context: __dirname,
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
APP_DIR + '/index.jsx',
],
output: {
publicPath: '/',
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
exclude: /(node_modules|bower_components)/,
query: { presets: ["env", "react"] }
},
{
test: /\.css$/,
// exclude: /node_modules/,
loader: 'style-loader!css-loader?importLoaders=1'
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass?sourceMap')
},
{
test: /\.less$/,
loader: 'style-loader!css-loader!postcss-loader!less-loader'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.png$/,
loader: "url-loader",
query: {
limit: 100000
}
},
{
test: /\.jpg$/,
loader: "url-loader"
},
{
test: /\.svg(\?.*)?$/,
loader: "url-loader",
query: {
limit: 10000,
mimetype: 'image/svg+xml'
}
},
{
test: /\.(woff2?)(\?.*)?$/,
loader: "url-loader",
query: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
{
test: /\.(ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
mimetype: 'application/octet-stream'
}
},
{
test: /\.eot(\?.*)?$/,
loader: 'file-loader'
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.less', '.json']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}
}),
// new UglifyJsPlugin(), for production server only
HtmlWebpackPluginConfig
],
devServer: {
historyApiFallback: true,
hot: true
}
}
index.jsx
import 'bootstrap/dist/css/bootstrap.css'
what I have tried various comibinations in place of above modules for loaders from github solution but none of them is working, see the trials
trial 1 ( using file loader)
{
test: /\.(jpg|png|woff|woff2|eot|ttf|svg)$/,
loader: 'file-loader?name=[path][name].[ext]?[hash]'
}
trial 2 ( using url loader)
{
test: /\.(woff(2)?|eot|ttf|otf)(\?[a-z0-9]+)?$/,
loader: 'url-loader?limit=100000'
}
trial 3 (using url loader with lower limit)
{
test: /\.(woff2?|ttf|eot|svg|png|jpe?g|gif)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=8192'
},
In webpack 4, you need:
{
test: /\.(woff|woff2|ttf|eot)$/,
use: 'file-loader?name=fonts/[name].[ext]!static'
}
eg use file-loader.
there is my config about fonts
{
test: /\.(woff|woff2|ttf|eot)$/,
use: 'file?name=fonts/[name].[ext]!static'
}
maybe is useful
--- added ---
resolve: {
extensions: ['.js', '.jsx', '.css', '.less', '.json'],
modules: ['node_modules', 'path/to/your/static_resource']
}
I installed a vue plugin in a project that i'm working and i was getting this error to.
I tried to follow the instructions, but i do not know it they are outdated. I'm sharing my solution. In webpack.config.js i added the following set:
module: {
rules: [
... --> other existing rules
{
test: /\.(woff|woff2|ttf|eot)$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]!static'
},
include: /node_modules/
}
]
}
I am using vue cli webpack and below code fixed the error
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
}
I am doing React/Redux and also got this error.
I added this line in my webpack.config.dev.js to solve the issue:
module: {
loaders: [
...,
{test: /\.png$/, loader: 'file'} // Line added
]
}
Then in my R/R codes, I used import (ES6) to require the image. Then I do:
<img src={myPNGImage} .../>
In PWA studio for Magento2 ,
You can add a line in webPackConfig.js as follows
config.module.rules.push({ test: /\.(woff|woff2|ttf|eot)$/, use: 'file-loader' });
This should do the job.
The accepted answer worked for me, however since webpack 4 the answer needs a slight update to use file-loader instead of just file, e.g.:
{
test: /\.(woff|woff2|ttf|eot)$/,
use: 'file-loader?name=fonts/[name].[ext]!static'
}