webpack-dev-server unable to import static files - webpack-dev-server

static files (such as .svg, .png and so on) won't load nor throw error at all.
would like to see them loaded.
[structure]
|--src
| |--modules
| | |--example.ts
| |--renderer
| | |--assets
| | | |--example.svg
| | |--app.ts
| | |--app.vue
| | |--app.scss
| | |--index.ts
| |--resources
| | |--example.json
| |--index.html
|--package.json
|--webpack
| |--webpack.config.js
| |--serve.js
| |--build.js
[app.vue]
<template>
<object type="image/svg+xml" data="#renderer/assets/example.svg"></object>
</template>
[webpack.config.js]
const path = require("path");
const webpack = require("webpack");
const vue_loader_plugin = require("vue-loader/lib/plugin");
const html_webpack_plugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/renderer/index.ts",
stats: "errors-only",
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
},
exclude: /node_modules/
},
{
test: /\.ts$/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/]
},
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: "vue-loader",
exclude: /node_modules/
},
{
test: /\.scss$/,
loader: ["vue-style-loader", "css-loader", "sass-loader"]
},
{
test: /\.(png|jpe?g|gif|svg)$/,
loader: "file-loader",
}
]
},
output: {
path: path.resolve(__dirname, "..", "dist"),
publicPath: "http://localhost:8080/",
filename: "bundle.js",
},
resolve: {
extensions: [".js", ".ts", ".vue", ".scss", ".json"],
alias: {
"#modules": path.resolve(__dirname, "..", "src", "modules"),
"#renderer": path.resolve(__dirname, "..", "src", "renderer"),
"#resources": path.resolve(__dirname, "..", "src", "resources")
}
},
plugins: [
new html_webpack_plugin({
template: "./src/index.html"
}),
new vue_loader_plugin(),
new webpack.HotModuleReplacementPlugin()
]
};

You need to use CopyWebpackPlugin plugin to copy static assets, like:
const CopyWebpackPlugin = require('copy-webpack-plugin');
plugins: [
...
new CopyWebpackPlugin([
{ from: './images/*.*', to: 'assets/', flatten: true }
]),
...
]

Related

Webpack Error - You may need an appropriate loader to handle this file type,

I was trying to add webpack config in my react project, but i am facing issue as when i run the project , i get an error which says -
ERROR in ./src/index.js 14:2
Module parse failed: Unexpected token (14:2)
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
|
| ReactDOM.render(
> <React.StrictMode>
| <App/>
| </React.StrictMode>,
here below is my configuration for webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: path.join(__dirname, "src", "index.js"),
output: {
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
},
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin(),
],
resolve: {
extensions: [".js", ".jsx"],
},
module: {
rules: [
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader, // instead of style-loader
"css-loader",
],
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: ["file-loader"],
},
{
test: /\.svg$/,
use: ["file-loader"],
},
],
},
};
Your configuration has 2 module keys. They conflict with each other. Merging them should resolve your issue:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: path.join(__dirname, "src", "index.js"),
output: {
path: path.resolve(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin(),
],
resolve: {
extensions: [".js", ".jsx"],
},
module: {
rules: [
{
test: /\.?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
},
},
},
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader, // instead of style-loader
"css-loader",
],
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: ["file-loader"],
},
{
test: /\.svg$/,
use: ["file-loader"],
},
],
},
};

Webpack5 config error: An appropriate loader to handle this file type

I'm trying to migrate webpack4 to webpack5. My project has both react and typescript files.
I'm running into below error:
ERROR in ./src/index.js 19:4
Module parse failed: Unexpected token (19:4)
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
>ReactDOM.render(
> > <Provider store={store}>
> | <App/>
> | </Provider>
,
webpack 5.11.1 compiled with 1 error in 67 ms
webpack.common.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
const moment = require('moment');
const CircularDependencyPlugin = require('circular-dependency-plugin');
module.exports = (...args) => {
const [
env,
{ configName }
] = args;
return {
entry: ['#babel/polyfill', './src/index.js'],
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: './index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[name].[chunkhash].css',
}),
new webpack.DefinePlugin({
__SNAPSHOT__: JSON.stringify(moment().format('MMMM Do YYYY, h:mm:ss a')),
__MODE__: JSON.stringify(env),
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: true,
allowAsyncCycles: false,
cwd: process.cwd(),
})
],
output: {
path: path.resolve(__dirname, 'build'),
chunkFilename: '[name].[chunkhash].js',
filename: '[name]_bundle.js',
publicPath: '/build/',
chunkLoading: false
},
target: ['web'],
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
},
},
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.(sa|sc)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: env === 'development',
},
},
'css-loader',
'postcss-loader',
'sass-loader',
]
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: ['url-loader']
}
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
port: 8888
}
}
};
try it removing:
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},

Configuring Webpack to required folder structure for build files

I have a ReactJS application, that was built using Webpack. So, in my webpack.config.js, I have return the required code to take a build, and everything builds into a 'build' file, in my project folder.
This is the current file structure:
Project
| -- build
| -- index.html
| -- bundle.js
| -- background.png
| -- avatar.png
However, I want my build files to take a separate structure, as shown below:
Project
| -- build
| -- templates
| -- index.html
| -- static
| -- js
| -- bundle.js
| -- images
| -- background.png
| -- avatar.png
My webpack.config.js is provided below. I tried tweaking it, and the structure was obtained, but the images failed to load. The HTML and JS worked without any issues, but the images just didn't load. Shown below is the unaltered code, which builds all the files into a single folder.
const HtmlWebPackPlugin = require("html-webpack-plugin");
var path = require('path');
const htmlWebpackPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
});
module.exports = {
entry: ["#babel/polyfill", './src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
devtool: "#eval-source-map",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.js?$/,
include: /(src[\/\\]js)/,
loader: 'babel-loader'
},
{
test: /\.jsx?$/,
include: /(src[\/\\]jsx)/,
loader: 'babel-loader'
},
{
test: /\.json?$/,
exclude: /(node_modules|bower_components)/,
loader: 'json-loader'
},
{
test: /\.css?$/,
loaders: ['style-loader', 'raw-loader']
},
{
test: /\.scss?$/,
loaders: ['style-loader', 'raw-loader', 'sass-loader', 'import-glob']
},
{
test: /\.(png|ico|gif)?$/,
loader: 'file-loader?limit=30000&name=[name].[ext]'
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [htmlWebpackPlugin]
};
In your webpack.config.js, set your filename to static/js/bundle.js. This will output your bundle in a newly created build/static/js directory:
module.exports = {
// ...
output: {
filename: 'static/js/bundle.js',
path: path.resolve(__dirname, 'build')
},
// ...
}
Then set the outputPath property of file-loader to static/images/
// ...
{
test: /\.(png|ico|gif)?$/,
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'static/images',
}
}
// ...

SyntaxError on setting state in React

Here's the error I'm receiving:
ERROR in ./src/components/CustomHeader.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (17:10)
15 | class CustomHeader extends Component {
16 |
> 17 | state = {activeItem: 'home'};
| ^
18 |
19 | handleItemClick = (e, {name}) => this.setState({activeItem:name});
20 |
Her is my webpack.config.js file:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: "cheap-eval-source-map",
entry: path.join(__dirname, 'src', 'index.js'),
output: {
path: path.join(__dirname, 'dist'),
filename: "bundle.js",
publicPath: '/'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src')
},
{
test: /\.jsx$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src')
},
{
test: /\.css$/,
loader: [ 'style-loader', 'css-loader' ],
include: path.join(__dirname, 'src'),
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.scss$/,
use: [{
loader: 'style-loader',
}, {
loader: 'css-loader',
}, {
loader: 'sass-loader',
}],
}
]
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
inline: true,
hot: true,
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
hash: true,
})
]
}
.babelrc file:
{
"presets": [
"react",
"env"
]
}
Do I need to change how I set state? Or is there something else that I need to import to my project? Any help would be appreciated. Thanks.
(Note: Code I'm using is taken straight from Semantic UI Examples at the moment.)
You need either stage-2 preset
OR
You can use babel-plugin-transform-class-properties.
if you don't want to use stage-2 and stick with more stable stages.
Try out your combinations on BabelJS and pick your poison.

Build Failure while using webpack production build

I am getting Module build failed: SyntaxError: Unexpected token Error.
I am getting this error while generating production build, before applying the Webpack production build configuration the same code was working earlier when using development build. Can you suggest me what i am doing wrong in webpack.config.js
Here is the Error
ERROR in ./src/index.jsx
Module build failed: SyntaxError: Unexpected token (10:4)
client |
client | 8 |
client | 9 | const App = () => (
client | > 10 | <Provider store={store}>
client | | ^
client | 11 | <AppRoute/>
client | 12 | </Provider>
client | 13 | );
Here is my webpack.config.js file code
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname, 'src');
const buildPath = path.join(__dirname, 'dist');
module.exports = {
devtool: 'source-map',
entry: {
app: path.resolve(sourcePath, 'index.jsx')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
sourcePath,
path.resolve(__dirname, 'node_modules')
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[chunkhash].js',
minChunks (module) {
return module.context && module.context.indexOf('node_modules') >= 0;
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true
},
output: {
comments: false
}
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})
],
context: staticSourcePath
}
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
template: path.join(sourcePath, 'index.html'),
path: buildPath,
filename: 'index.html',
minify: {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new PreloadWebpackPlugin({
rel: 'preload',
as: 'script',
include: 'allChunks',
fileBlacklist: [/\.(css|map)$/, /base?.+/]
}),
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'defer'
}),
new ExtractTextPlugin({
filename: '[name].[contenthash].css',
allChunks: true
}),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
threshold: 10240,
minRatio: 0.8
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
'babel-loader'
]
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { minimize: true } },
'postcss-loader',
'sass-loader'
]
})
},
{
test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
use: 'file-loader?name=assets/[name]-[hash].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
use: [
'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
],
include: staticSourcePath
}
]
}
};
And Here is my index.jsx code.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './_helpers';
import AppRoute from './pages/approute';
import 'react-table/react-table.css';
const App = () => (
<Provider store={store}>
<AppRoute/>
</Provider>
);
ReactDOM.render(<App />, document.getElementById('app'));
As pointed out in a comment there has to be something with babel configuration that webpack can't transpile JSX syntax.
Check out if you have babel-preset-react installed and turned on:
"presets": [
"react"
],
Little nitpick - use caching for faster incremental builds:
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
},
Final update in webpack.config.js
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['react', 'es2015', 'stage-3']
}
}

Resources