Webpack cannot find image when imported - module not found - webpack-dev-server

I am using webpack dev server to serve up a simple Typescript app. In it, I am trying to load an image dynamically in the Typescript like so:
import img from "./image.png";
const myImg = new Image();
myImg.addEventListener("load", ...);
myImg.src = img;
The HTML, TS, and image files are all sitting right next to each other, so I use the relative path to grab the image. However, webpack complains saying "./image.png" is not a module. I am almost certain it must be a configuration issue. Here are the relevant files (with some values changed to generic values):
package.json
{
"name": "my_project",
"version": "0.1.0",
"description": "My project",
"main": "index.js",
"scripts": {
"build-prod": "webpack --config webpack.prod.js",
"start-dev": "webpack-dev-server --config webpack.dev.js"
},
"author": "Cyle Ven Dawson",
"license": "MIT",
"private": true,
"devDependencies": {
"awesome-typescript-loader": "^5.2.1",
"css-loader": "^1.0.0",
"file-loader": "^2.0.0",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.9.3",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.0",
"tslint": "^5.11.0",
"typescript": "^3.0.3",
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.8",
"webpack-merge": "^4.1.4"
}
}
webpack.dev.js
const merge = require("webpack-merge");
const commonConfig = require("./webpack.common");
module.exports = merge(
commonConfig,
{
"devServer" : {
"allowedHosts": [
"dev.example.com"
],
"disableHostCheck": true,
"host": "1.2.3.4",
"port": 12345,
"public": "dev.example.com:12345"
},
"mode": "development"
}
);
webpack.common.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const TsConfigPathsPlugin = require("awesome-typescript-loader").TsConfigPathsPlugin;
module.exports = {
"entry": "./src/index.ts",
"module": {
"rules": [
{
"include": /src/,
"test": /\.ts$/,
"use": {
"loader": "awesome-typescript-loader"
}
},
{
"include": /src/,
"test": /\.scss$/,
"use": [
"style-loader",
"css-loader",
"sass-loader"
]
},
{
"include": /src/,
"test": /\.(png|svg|jpg|gif)$/,
"use": [
'file-loader'
]
}
]
},
"output": {
"publicPath": "/"
},
"plugins": [
new HtmlWebPackPlugin({
"filename": "./index.html",
"template": "./src/index.html"
})
],
"resolve": {
"extensions": [".ts", ".js"],
"plugins": [
new TsConfigPathsPlugin({
tsconfig: __dirname + '/tsconfig.json',
compiler: 'typescript'
})
]
},
};

I leave this here in case anyone comes here from google.
You must tell typescript that the png image is a module.
The way you do this is inside of the assets folder or where ever you are storing you images make a file called index.d.ts
Inside this file put the following:
declare module '*.png' {
const value: any
export = value;
}
This will give you the ability to import a png image as a module and make Typescript happy. I believe this will work for .wav, .gif, .jpg ect. You would just need to declare each one in the index.d.ts file.
I hope this helps some one.

Related

Babel configuration file issue

I have an issue with babel and Webpack. I shared configurations. I am getting below error while i am running webpack build command. However i already added #babel/preset-react in .babelrc (also tried babel.config.json) files. I need some suggestion for solve this error.
{
"name": "#mahiraltinkaya/react-image-upload",
"version": "1.2.1",
"description": "",
"main": "dist/index.js",
"scripts": {
"build": "webpack --mode production"
},
"repository": {
"type": "git",
"url": "git+ssh://git#github.com/mahiraltinkaya/react-file-upload.git"
},
"keywords": [
"react",
"next",
"react-image",
"image-drag-n-drop"
],
"author": "Mahir Altinkaya",
"license": "ISC",
"bugs": {
"url": "https://github.com/mahiraltinkaya/react-file-upload/issues"
},
"homepage": "https://github.com/mahiraltinkaya/react-file-upload#readme",
"devDependencies": {
"#babel/cli": "^7.20.7",
"#babel/core": "^7.20.12",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.2",
"css-loader": "^6.7.3",
"style-loader": "^3.3.1",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"prop-types": "^15.8.1",
"react": "^16.14.0"
}
}
babel.config.json
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
webpack.config.json
var path = require("path");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
path: path.resolve("dist"),
filename: "index.js",
libraryTarget: "commonjs2",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.css$/,
loader: "css-loader",
},
],
},
externals: {
react: "react",
},
};
For some reason, your file babel.config.json is not parsed. webpack is not reading it. convert it to
.babelrc
or convert it to babel.config.js and have this
module.exports={"presets": ["#babel/preset-env", "#babel/preset-react"]}

Webpack live reload says "nothing changed" even if I modify a file. Why?

I have a react project and I'm using Webpack (webpack-dev-server) for my development.
Everything compiles well, and when I make a change in my file (for the first time), the live reloading works well.
BUT, after changing the same file twice (or more), the live reloading stop working. In the console it says "nothing changed" even when I made a change.
Looks like the webpack-dev-server memory doesn't pick up the change. Any idea why?
Webpack Config
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ProvidePlugin } = require("webpack");
module.exports = {
target: "web",
mode: "development",
entry: ["regenerator-runtime/runtime.js", "./src/index.js"],
devtool: "inline-source-map",
devServer: {
historyApiFallback: true,
hot: true,
port: 8080,
static: "./dist",
watchFiles: "src/**/*,js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "index_bundle.js",
},
resolve: { extensions: ["*", ".js", ".jsx"] },
module: {
rules: [
{
test: /\.(jsx|js)$/,
exclude: /(node_modules)/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/env", "#babel/react"],
},
},
],
},
{
test: /\.css$/,
// exclude: /node_modules/,
use: ["style-loader", "css-loader"],
},
{
test: /\.svg$/,
use: [
{
loader: "svg-url-loader",
options: {
limit: 10000,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "src/index.html",
title: "Development",
}),
new ProvidePlugin({
React: "react",
}),
],
};
Package.json
{
"name": "timerfrontend",
"version": "1.0.0",
"main": "index.js",
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack serve",
"create": "webpack -w",
"build": "webpack -p"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.16.5",
"#babel/preset-env": "^7.16.5",
"#babel/preset-react": "^7.16.5",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"html-webpack-plugin": "^5.3.1",
"style-loader": "^3.3.1",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0"
},
"dependencies": {
"#apollo/client": "^3.5.6",
"#apollo/link-context": "^2.0.0-beta.3",
"#apollo/react-hooks": "^4.0.0",
"#auth0/auth0-react": "^1.8.0",
"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link-http": "^1.5.17",
"bootstrap": "^5.0.1",
"dayjs": "^1.10.5",
"npm-force-resolutions": "^0.0.10",
"prop-types": "^15.7.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.1.1",
"regenerator-runtime": "^0.13.9",
"svg-url-loader": "^7.1.1"
},
"description": "",
"resolutions": {
"react": "17.0.2",
"graphql": "16.1.0"
}
}
I found the solution (hint: its weird)
I realized that my Webpack live reloading was working on my other components (except the I had issue with).
I finally resolved to deleting that component and create a new one (exact copy) and then it worked perfectly!?
I still don't know why Webpack didn't like this component specifically...
It was happening to me, I checked the files and class names, they have to be exactly the same, including caps and lowercase letters
In my case, the file I was modified is not being use anywhere in project, so webpack does not recognize it.
After import and use it in the code, then it work fine

Vaadin into Angular v1.x with through Webpack bundle

I am trying to bundle Vaadin in a single file to be loaded inside my portal (which running with AngularJS V1.x) following this guide. It fails because is using an old configuration (which I fixed for the development mode but I didn't for the production one) and because I could bundle the references left in the node modules instead of copied inside the bundle.
So I tried with a new webpack setup with this configuration:
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
var config = {
// TODO: Add common Configuration
mode: 'development',
performance: {
hints: false,
maxEntrypointSize: 5512000,
maxAssetSize: 5512000
},
devServer: {
contentBase: './dist',
},
module: {}
};
var jsConfig = Object.assign({}, config, {
entry: {
index: './src/index.js',
vaadin: './src/webcomponentsjs/main.js'
},
optimization: {
minimize: true
},
plugins: [
new HtmlWebpackPlugin({
title: 'Vaadin Library',
template: './src/index.html'
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: false
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['transform-class-properties']
}
}
}
],
}
});
module.exports = [
jsConfig
];
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": true,
"dependencies": {
"lodash": "^4.17.21",
"web-animations-js": "^2.3.2"
},
"devDependencies": {
"#babel/cli": "^7.14.5",
"#babel/core": "^7.14.6",
"#babel/plugin-syntax-top-level-await": "^7.14.5",
"#babel/plugin-transform-template-literals": "^7.14.5",
"#babel/preset-env": "^7.14.5",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^8.2.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"css-loader": "^5.2.6",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^5.3.1",
"install": "^0.13.0",
"mini-css-extract-plugin": "^1.6.0",
"npm": "^7.17.0",
"sass": "^1.35.1",
"sass-loader": "^12.1.0",
"script-ext-html-webpack-plugin": "^2.1.5",
"style-loader": "^2.0.0",
"url-loader": "^4.1.1",
"webpack": "^5.39.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "echo \"Bundling Vaadin library to less files and convert to ES5 with Webpack and Babel (loader)\" && webpack",
"start": "webpack serve --open"
},
"keywords": [],
"author": "",
"license": "ISC"
}
And here the errors (for each component imported in index.js):
ERROR in ./src/index.js 2:0-31
Module not found: Error: Can't resolve '#vaadin/vaadin-button' in '/Users/username/Dev/current/webpack-vaadin/src'
Did you mean './#vaadin/vaadin-button'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.
Did anyone already manage to import Vaadin into an angularJs application? How did you do or could you point me at the right place in the documentation (which I didn't find as very new with this FW)?
Thanks in advance.

Jest Unexpected Identifier require

I'm trying to set up Jest to test my app as it grows. I'm getting the below error:
SyntaxError: Unexpected identifier
> 1 | const screenSize = require("../src/index.js").screenSize;
| ^
I'm using Phaser 3, Webpack, Babel, and React.
I'm relatively new to all except React.
I followed Jest's Getting Started tutorial and using with webpack tutorial, but I'm still getting the error.
package.json
{
"name": "phaser3-project-template",
"version": "1.1.0",
"description": "A Phaser 3 Project Template",
"main": "src/index.js",
"scripts": {
"build": "webpack --config webpack/prod.js ",
"start": "webpack-dev-server --config webpack/base.js --open",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/photonstorm/phaser3-project-template.git"
},
"author": "Richard Davey <rdavey#gmail.com> (http://www.photonstorm.com)",
"license": "MIT",
"licenseUrl": "http://www.opensource.org/licenses/mit-license.php",
"bugs": {
"url": "https://github.com/photonstorm/phaser3-project-template/issues"
},
"homepage": "https://github.com/photonstorm/phaser3-project-template#readme",
"devDependencies": {
"#babel/core": "^7.4.3",
"#babel/plugin-proposal-class-properties": "^7.4.0",
"#babel/preset-env": "^7.4.3",
"#babel/preset-react": "^7.0.0",
"babel-jest": "^24.7.1",
"babel-loader": "^8.0.5",
"clean-webpack-plugin": "^1.0.0",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"jest": "^24.7.1",
"path": "^0.12.7",
"raw-loader": "^1.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"terser-webpack-plugin": "^1.2.1",
"webpack": "^4.28.3",
"webpack-cli": "^3.2.1",
"webpack-dev-server": "^3.1.14",
"webpack-merge": "^4.2.1"
},
"dependencies": {
"babel-core": "^6.26.3",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^2.1.1",
"phaser": "^3.16.2",
"react-redux": "^7.0.2",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"style-loader": "^0.23.1"
},
"jest": {
"modulePaths": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"moduleNameMapper": {
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
webpack/base.js
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports = {
mode: "development",
devtool: "eval-source-map",
entry: "./src/index.js", //do we need this?
output: {
path: path.resolve("dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: "style-loader" }, { loader: "css-loader" }]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: "babel-loader"
},
{
test: [/\.vert$/, /\.frag$/],
use: "raw-loader"
},
{
test: /\.(gif|png|jpe?g|svg|xml)$/i,
use: "file-loader"
}
]
},
plugins: [
new CleanWebpackPlugin(["dist"], {
root: path.resolve(__dirname, "../")
}),
new webpack.DefinePlugin({
CANVAS_RENDERER: JSON.stringify(true),
WEBGL_RENDERER: JSON.stringify(true)
}),
new HtmlWebpackPlugin({
template: "./index.html",
filename: "index.html",
inject: "body"
})
]
};
.babelrc.js
const presets = [
[
"#babel/env",
{
targets: {
browsers: [">0.25%", "not ie 11", "not op_mini all"],
node: "current"
},
modules: false
}
],
"#babel/preset-react"
];
const plugins = ["#babel/plugin-proposal-class-properties"];
module.exports = { presets, plugins };
jest.config.js
"use strict";
module.exports = {
testMatch: ["<rootDir>/**/*.test.js"],
testPathIgnorePatterns: ["/src/", "node_modules"]
};
index.test.js
const screenSize = require("../src/index.js").screenSize;
//import toBeType from "jest-tobetype";
console.log(screenSize);
test("screenSize is an object", () => {
expect(typeof screenSize).toBe("object");
});
Github Repo
How can I get Jest to process the es6 syntax?
Require is a node environment syntax for importing variables, and Jest runs in node. More background on the differences between import/require and node can be seen in this SO question
You can add support for this with
npm install --save-dev #babel/plugin-proposal-class-properties #babel/plugin-transform-modules-commonjs
and include these as presets in your babelrc.js
const presets = [
[
"#babel/env",
{
targets: {
browsers: [">0.25%", "not ie 11", "not op_mini all"]
},
modules: false
}
],
"#babel/preset-react"
];
const plugins = [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-modules-commonjs"
];
module.exports = { presets, plugins };
The above code will still run into a number of errors details to resolve those can be seen here: https://medium.com/#Tnodes/setting-up-jest-with-react-and-phaser-422b174ec87e

REact.js, react-toolbox syntax error?

Why am I getting this syntax error??? Driving me nuts, I know its some simple...I basically copied the example code from here:
http://react-toolbox.com/#/components/input
And I am simply trying to import it into here:
Any suggestions are hugely appreciated...
webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: __dirname,
devtool: 'inline-source-map',
entry: [
'webpack-hot-middleware/client',
'./app/index.jsx'
],
output: {
path: path.join(__dirname, 'build'),
filename: 'react-toolbox.js',
publicPath: '/'
},
resolve: {
extensions: ['', '.jsx', '.scss', '.js', '.json'],
modulesDirectories: [
'node_modules',
path.resolve(__dirname, './node_modules')
]
},
module: {
loaders: [
{
test: /(\.js|\.jsx)$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets:['es2015','react']
}
}, {
test: /(\.scss|\.css)$/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass?sourceMap!toolbox')
}
]
},
toolbox: {
theme: path.join(__dirname, 'app/toolbox-theme.scss')
},
postcss: [autoprefixer],
plugins: [
new ExtractTextPlugin('react-toolbox.css', { allChunks: true }),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
};
package.json:
{
"name": "react-toolbox-example",
"version": "0.11.4",
"description": "A set of complementary tools to ReactJS.",
"author": "React Toolbox Team (http://github.com/react-toolbox)",
"contributors": [
{
"name": "Javi Jimenez Villar",
"url": "http://soyjavi.com/",
"email": "javi.jimenez.villar#gmail.com"
},
{
"name": "Javi Velasco Arjona",
"url": "http://javivelasco.com/",
"email": "javier.velasco86#gmail.com"
}
],
"bugs": {
"url": "https://github.com/react-toolbox/react-toolbox/issues",
"email": "issues#react-toolbox.com"
},
"keywords": [
"react",
"react-component",
"material design",
"toolbox",
"components"
],
"license": "MIT",
"devDependencies": {
"autoprefixer": "6.3.6",
"babel-core": "6.7.7",
"babel-eslint": "6.0.3",
"babel-loader": "^6.0.1",
"babel-plugin-react-transform": "2.0.2",
"babel-preset-es2015": "^6.1.4",
"babel-preset-react": "^6.1.4",
"classnames": "^2.2.1",
"cross-env": "^1.0.1",
"css-loader": "0.23.1",
"express": "^4.13.3",
"extract-text-webpack-plugin": "1.0.1",
"node-sass": "3.4.2",
"normalize.css": "^4.0.0",
"postcss-loader": "0.8.2",
"react": "^15.0.0",
"react-addons-css-transition-group": "^15.0.0",
"react-dom": "^15.0.0",
"react-toolbox": "^0.16.2",
"react-transform-catch-errors": "^1.0.0",
"react-transform-hmr": "^1.0.1",
"redbox-react": "1.2.3",
"sass-loader": "3.2.0",
"style-loader": "0.13.1",
"toolbox-loader": "0.0.3",
"webpack": "1.13.0",
"webpack-dev-middleware": "1.6.1",
"webpack-hot-middleware": "2.10.0"
},
"scripts": {
"start": "node ./server",
"build": "cross-env NODE_ENV=production UV_THREADPOOL_SIZE=100 webpack --config ./webpack.config",
"deploy": "gh-pages -d build"
},
"repository": "github:react-toolbox/react-toolbox-example"
}
.babelrc
{
"presets": ["es2015", "stage-0", "react"]
}
https://github.com/malexanders/react-toolbox-example
Your code is crashing on the class property syntax which is currently a stage 1 Ecmascript proposal. In order for babel to transpile this correctly you need the stage-1 preset. I would say it's pretty common to have the stage-0 preset which includes everything above it as well.
You can even see from your repo's .babelrc file already wanting to include stage-0 preset:
{
"plugins": ["es2015", "stage-0"]
}
However it looks like you're overriding this file in your webpack config using the query key here:
query: {
presets:['es2015', 'react']
}
So what you need to do to fix this is
1) Install stage-0 preset
npm install --save-dev babel-preset-stage-0
2) Add the preset to your webpack.config.js query: presets array
query: {
presets: ['es2015', 'react', 'stage-0']
}
The equals should be a colon. Additionally, there needs to be a comma after the last curly brace.

Resources