Webpack runs Babel against PNG - ecmascript-6

Here is my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: __dirname,
entry: {
javascript: './static/jsx/main.jsx'
},
output: {
path: path.resolve('./static/js/app/'),
filename: 'bundle.js'
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'source-map'
}
],
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader?limit=25000',
include: path.resolve('./static/images/')
}
]
},
};
Here is example of using png in a jsx file
import L from 'leaflet';
import { LayersControl, Marker, Popup } from 'react-leaflet';
const src = require('./marker-icon-red.png');
//Extend the Default marker class
let RedIcon = L.Icon.Default.extend({
options: {
iconUrl: src
}
});
let redIcon = new RedIcon();
When I run webpack for my jsx files (using gulp)
gulp.task('transform', function() {
return gulp.src(path.JS)
.pipe(webpack( require('./webpack.config.js') ))
.on('error', swallowError)
.pipe(gulp.dest(path.DEST_BUILD));
});
I get this error
[15:14:10] Starting 'transform'...
Error in plugin 'webpack-stream'
Message:
./static/jsx/map/markers/marker-icon-red.png
Module parse failed: D:\work\Cycling\static\jsx\map\markers\marker-icon-red.png
Unexpected character '?' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '?' (1:0)
at Parser.pp$4.raise (D:\work\Cycling\node_modules\webpack\node_modules\acor
n\dist\acorn.js:2221:15)
at Parser.pp$7.getTokenFromCode (D:\work\Cycling\node_modules\webpack\node_m
odules\acorn\dist\acorn.js:2756:10)
at Parser.pp$7.readToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2477:17)
at Parser.pp$7.nextToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2468:15)
at Parser.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:515:10)
at Object.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:3098:39)
at Parser.parse (D:\work\Cycling\node_modules\webpack\lib\Parser.js:902:15)
at DependenciesBlock.<anonymous> (D:\work\Cycling\node_modules\webpack\lib\N
ormalModule.js:104:16)
at DependenciesBlock.onModuleBuild (D:\work\Cycling\node_modules\webpack-cor
e\lib\NormalModuleMixin.js:310:10)
at nextLoader (D:\work\Cycling\node_modules\webpack-core\lib\NormalModuleMix
in.js:275:25)
# ./static/jsx/map/markers/parkings_markers.jsx 19:10-42
[15:14:21] Version: webpack 1.13.2
Asset Size Chunks Chunk Names
bundle.js 1.48 MB 0 [emitted] javascript
ERROR in ./static/jsx/map/markers/marker-icon-red.png
Module parse failed: D:\work\Cycling\static\jsx\map\markers\marker-icon-red.png
Unexpected character '?' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '?' (1:0)
at Parser.pp$4.raise (D:\work\Cycling\node_modules\webpack\node_modules\acor
n\dist\acorn.js:2221:15)
at Parser.pp$7.getTokenFromCode (D:\work\Cycling\node_modules\webpack\node_m
odules\acorn\dist\acorn.js:2756:10)
at Parser.pp$7.readToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2477:17)
at Parser.pp$7.nextToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2468:15)
at Parser.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:515:10)
at Object.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:3098:39)
at Parser.parse (D:\work\Cycling\node_modules\webpack\lib\Parser.js:902:15)
at DependenciesBlock.<anonymous> (D:\work\Cycling\node_modules\webpack\lib\N
ormalModule.js:104:16)
at DependenciesBlock.onModuleBuild (D:\work\Cycling\node_modules\webpack-cor
e\lib\NormalModuleMixin.js:310:10)
at nextLoader (D:\work\Cycling\node_modules\webpack-core\lib\NormalModuleMix
in.js:275:25)
# ./static/jsx/map/markers/parkings_markers.jsx 19:10-42
[15:14:21] Finished 'transform' after 11 s
As I understood it's babel tries to read png file, although I told webpack that png files should be treated by url-loader not babel.
What am I doing wrong?
Thanks for help!

Your url-loader config is set to only consider images from ./static/images, because of the include property:
{
test : /\.(jpg|png)$/,
loader : 'url-loader?limit=25000',
include : path.resolve('./static/images/')
}
However, the image you're trying to require is located in a different directory (./static/jsx/map/markers/).
If you remove the include, it'll probably work.

Renaming img1.PNG to img1.png solved it in my case.

Related

VueJS3, How to parse a csv file in my src folder?

I am using VueJS3 cli. New in VueJS here :)
I have a csv file in my folder:
/src/db/example.csv
I would like to load it and use it as data structure, in the same way I do it with json files:
import jsonExample from "#/db/example.json";
If I try to do it with a csv file I get this:
import csvExample from "#/db/example.csv";
// 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
I tried to install the csv-loader
yarn add csv-loader
But I don't know where to add the configuration (https://www.npmjs.com/package/csv-loader#user-content-usage) I don't have any webpack configuration file :/, I have:
babel.config.js
jsconfig.json
package.json
vue.config.js
yarn.lock
I also tried to use papaparse directly:
this.$papa.parse("#/db/example.csv");
But I get this error:
{
"data": [
[
"#/db/exaple.csv"
]
],
"errors": [
{
"type": "Delimiter",
"code": "UndetectableDelimiter",
"message": "Unable to auto-detect delimiting character; defaulted to ','"
}
],
"meta": {
"delimiter": ",",
"linebreak": "\n",
"aborted": false,
"truncated": false,
"cursor": 19
}
}
Obviously it is interpreting the Path as a the Data.
Following instructions here: https://cli.vuejs.org/guide/webpack.html#working-with-webpack
I configured the loader like this:
// vue.config.js
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack: config => {
// csv-loader
config.module
.rule('csv-loader')
.test(/\.csv$/)
.use('csv-loader')
.loader('csv-loader')
.end()
}
})
Now this is working:
import data from "#/db/example.csv";
PD: I had to restart yarn serve

Grunt bake file include cannot read file

I have the following index.html in my root directory
When I run grunt I get the following error:
Verifying property bake.my_target exists in config...OK
Files: index.html -> dist/index.html
Options: content="content.json", section=null, semanticIf=false, basePath="", transforms={}, parsePattern={}, variableParsePattern={}, removeUndefined
Reading content.json...OK
Parsing content.json...OK
Reading index.html...OK
Reading /includes/test.html...ERROR
Warning: Unable to read "/includes/test.html" file (Error code: ENOENT). Use --force to continue.
This is my gruntfile.js:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
},
bake: {
my_target: {
options: {
content: "content.json"
},
files: {
"dist/index.html": "index.html"
}
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks( "grunt-bake" );
// Default task(s).
grunt.registerTask('default', ['uglify', 'bake']);
};
What am I doing wrong. I just followed the docs from this link: https://www.npmjs.com/package/grunt-bake
It looks like grunt-bake has a bug with include path parsing if baking file is placed at root of folder. Try to put your index.html to some folder, like 'src/index.html' - this worked for me (after few hours wasted).
Source code of grunt-bake contains this line so it always put '/' to "include" file path - I guess this is why it does not work for files at root folder:
directory( filePath ) + "/" + includePath

#rollup/plugin-json with typescript not working

I have a valid appsettings.json file (according to jsonlint.com), I've set the tsconfig resolveJsonModule option to true. I'm importing #rollup/plugin-json and I've tried calling it at every position in the plugins chain. But I always get:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
So the plugin is firing (I think), but it can't parse the file, which seems to be valid. Rollup config looks like this:
import typescript from '#rollup/plugin-typescript';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from "#rollup/plugin-commonjs";
import dev from 'rollup-plugin-dev';
import copy from 'rollup-plugin-copy';
import replace from '#rollup/plugin-replace';
// Loaders for non-ts/js file types
import postcss from 'rollup-plugin-postcss';
import image from '#rollup/plugin-image';
import json from '#rollup/plugin-json';
console.log(`Node env is ${process.env.NODE_ENV}`);
// console.debug(process);
let isDevEnv = process.env.NODE_ENV === 'development';
let useMsw = process.env.USE_MSW;
const extensions = ['.cjs', '.js', '.jsx', '.json', '.ts', '.tsx', '.css', '.png'];
// const intro = useMsw
// ? 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = true'
// : 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = false';
const intro = `global = window; window.NODE_ENV = process.env.NODE_ENV; ${useMsw ? 'window.USE_MSW = true;' : ''}`;
export default {
input: [
'src/index.tsx'
],
output: {
intro: intro,
file: './dist/bundle.js',
format: 'es',
sourcemap: isDevEnv,
inlineDynamicImports: true,
},
plugins: [
postcss({}),
resolve({
extensions: extensions,
browser: true
}),
commonjs(),
typescript(),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
image(),
copy({
targets: [
{src: './src/index.html', dest: './dist/'},
{src: './src/mockServiceWorker.js', dest: './dist/'}
],
verbose: true
}),
isDevEnv && dev('dist', {
host: 'localhost'
}),
json(),
]
};
tsconfig looks like this:
{
"compilerOptions": {
"declaration": false,
"module": "ESNext",
"noImplicitAny": true,
"target": "ES2015",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"moduleResolution": "Node",
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": [
"src/**/*.tsx",
"src/**/*.ts",
"declaration.d.ts",
"src/components/TabularVIew/GridContainer/hooks"
],
"exclude": ["node_modules"]
}
and the actual json file looks like this:
{
"HUB_URL": "theHubUrl",
"AUTH_ENDPOINT": "https://localhost:44330/API/Dispatch/Authentication/v1.0/authenticate",
"POSITION_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/position",
"SUMMARY_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/summaries",
"GLOBAL_TLM": 1,
"PERIOD_LENGTH_MINUTES": 30,
"EFA_BLOCKS": [
[23,0,1,2],
[3,4,5,6],
[7,8,9,10],
[11,12,13,14],
[15,16,17,18],
[19,20,21,22]
]
}
and the rollup output is this:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
Pretty frustrating because on one line it says 'plugin json can't parse', then the next log line tells me I need plugin json???. Invalid file, file not found, plugin not installed, these I could understand. Possibly a clash between tsc and the plugin. Out of ideas..
Suggestions welcome.
Thanks.
The reason for that can be the json file encoding is utf8withbom. Try to encode the file as utf8.
Not really an answer, but the behaviour appears to be linked to some aggressive caching. Either by npm or typescript. I opened up the project in vscode, hosed node_modules, ran npm install, usual drill.. created a new JSON file, installed the rollup json plugin, and it built. Sum total of learning: 0;

Webpack dev server configuration refuse to work with full path to index

Hello I am trying to understand why does webpack dev server refuse to work with full path to my index.js. (I am using webpack with babel to build reactJS.)
At the moment my webpack.config is located in the same directory as my index.js file and due to that the declaration of the entry point of my index.js is just "./index". Here is how my webpack.config looks like:
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: __dirname
}]
}};
With this configuration my project is build by babel and works just fine on the server!
My problem comes when I tried to specify a full path of my index.js entry point. I need that because I want to externalize the webpack and it's configuration from my FE code. To be sure that it will work I first tried not to rely that webpack.config and index.js are in the same directory but to specify the path of the index as full path name:
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'D:/projects/myProject/index'
]
With this config babel seem to be able to navigate to the index.js and start compiling it, but it does encounter an unexpected (for me) error during the parse:
ERROR in D:/projects/myProject/index.js
Module parse failed: D:/projects/myProject/index.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import 'babel-core/polyfill';
|
| import React from 'react';
# multi main
What do I miss, why webpack makes difference between relatively configured index.js and full path one?
(I made sure that the full path is correct)
Thanks!
After a bit annoying investigation it appeared that my problem is specifying the Windows drives in uppercase. For some reason it appear that the index.js location full path should start with lowercase drive letter!
Hopefully this experience may be helpful to others.
Try using:
d:/Folder1/folder2/index.js
instead of
D:/Folder1/folder2/index.js

Protractor-cucumber report: result.json is empty

After i follow this question Cucumber HTML report with Protractor to add this line to config file resultJsonOutputFile: 'report.json', i can generate report.json file but this file is empty after i run my test.
---------------conf.js--------------
exports.config = {
allScriptTimeout: 60000, //To set up a timeout for each test executed on Protractor
baseUrl: 'http://localhost/wp/index.php',
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
//seleniumServerJar: 'selenium-server-standalone-2.48.2.jar',
framework: 'cucumber',
specs: [
'Feature/login.feature'
],
capabilities: {
browserName: 'firefox',
},
onPrepare : function () {
//driver.manage().window().setSize( width, height );
global.driver = browser.driver;
browser.ignoreSynchronization = true;
},
resultJsonOutputFile: 'report.json',
cucumberOpts: {
require: 'Feature/Steps/*_steps.js',
format: 'pretty',
defaultTimeoutInterval: 30000
}
};
Am i doing wrong or missing with my config? Could you help me give a guide to generate report for protractor-cucumber? Thank so much.
Changing the following code should solve the issue. (Refresh the folder in IDE to view the report.json)
// resultJsonOutputFile: 'report.json',
cucumberOpts: {
require: 'Feature/Steps/*_steps.js',
format: 'pretty',
format:'json:../report.json'
}