Webpack: "Module parse failed" - gulp

1.When I Execute command line, the Error is as follows:
D:\mypro\Demo\webpack\webpackgulp>webpack
Hash: d6b7d6bad8ca0746b6ec
Version: webpack 1.13.1
Time: 46ms
[0] ./src/main.js 0 bytes [built] [failed]
ERROR in ./src/main.js
Module parse failed: D:\mypro\Demo\webpack\webpackgulp\src\ma
ken (7:16)
You may need an appropriate loader to handle this file type.
2.Related configuration is as follows:
(1)Document structure:
(2)webpack.config.js:
module.exports = {
entry: "./src/main.js",
output: {
filename: "build.js",
path: __dirname
},
module: {
loaders: [
{
test: /\.less$/,
loader: "style!css!less"
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: []
};
(3)Entry file is main.js:
// css
require('../css/main.less');
var ContentMode = React.createClass({
render: function(){
return (
<div className="ContentMode">
<div class="contents">{this.props.contents}</div>
{this.props.children}
</div>
)
}
});
var Page = React.createClass({
render: function(){
return (
<div className="homepage">
<ContentMode contents ="longen">this is one comment</ContentMode >
<ContentMode contents ="longen2">this is two comment</ContentMode >
</div>
)
}
});
/* init to content container */
React.render(
React.createElement(Page,null),document.getElementById("content")
);
(4)node_modules:
3.How to solve this problem?

Related

pixi.js import issue with gulp & webpack

I have this gulp config file: (I removed some functions that do not interact with js)
const { src, dest, parallel, series, watch } = require('gulp')
const notify = require('gulp-notify')
const sourcemaps = require('gulp-sourcemaps')
const browserSync = require('browser-sync').create()
const del = require('del')
const webpackStream = require('webpack-stream')
const uglify = require('gulp-uglify-es').default
function scripts() {
return src('./src/assets/js/pages/*.js')
.pipe(
webpackStream({
mode: 'development',
output: {
filename: '[name].js',
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env']],
},
},
},
],
},
})
)
.pipe(sourcemaps.init())
.pipe(uglify().on('error', notify.onError('')))
.pipe(sourcemaps.write('.'))
.pipe(dest('./app/assets/js'))
.pipe(browserSync.stream())
}
function watchFiles() {
browserSync.init({
server: {
baseDir: './app',
},
})
watch('./src/*.html', htmlInclude)
watch('./src/partials/**/*.html', htmlInclude)
watch('./src/assets/scss/**/*.scss', styles)
watch('./src/assets/images/**/*', imgToApp)
watch('./src/assets/svg/**.svg', svg)
watch('./src/assets/fonts/**/*', fonts)
watch('./src/assets/js/**/*.js', scripts)
watch('./src/assets/fav.ico', favIcon)
}
function favIcon() {
return src('./src/assets/fav.ico').pipe(dest('./app/assets/'))
}
function clean() {
return del(['app/*'])
}
module.exports = {
styles,
watchFiles,
default: series(
clean,
parallel(favIcon, htmlInclude, imgToApp, svg, fonts, styles, scripts),
watchFiles
),
}
So, when I try to import Pixi.js
import * as PIXI from 'pixi.js';
my js code doesn't work at all and the worst thing is that there are no errors in the console.
Also I need hsl-to-hex module in my project and I just import it and everything works
I tried this variant of importing import PIXI from 'pixi.js/dist/pixi.js';
Also tried to use some gulp plugins, but I not really understand what they do, so it didn't give any result

Splitting HTML code into multiple files using webpack

I'm trying desperately to split my HTML into multiple files using Webpack. I've tried the "<%= require() %>" method but doesn't work. Only work with my images. See my webpack config below. Basically what I wanna do is this:
file1.html
<h1>This is my file number 1</h1>
file 2.html
<h1>This is my file number 2</h1>
<%= require("file1.html") %>
And then webpack when rendering the index.html file, will bundle those two files together.
This is my webpack.config.js:
const path = require("path")
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");
module.exports = {
entry: "./src/assets/js/index.js",
mode: "development",
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, "dist"),
clean: {
keep: /images\//, // Keep these assets under 'ignored/dir'.
},
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "./"
}
},
{
loader: 'css-loader',
options: {importLoaders: 2, url: false},
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
config: path.resolve(__dirname, 'postcss.config.js'),
},
},
},
],
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
filename: "[name].[hash:6].[ext]",
outputPath: 'images/',
emitFile: true,
esModule: false
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Caching',
template: "./src/template.html"
}),
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css",
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
],
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
},
},
},
},
}
Any help is more than welcome.
Thanks in advance!
It is not really possible out-of-box with either Webpack or html-webpack-plugin. However, you have multiple possible options to achieve this.
Option 1
Read the HTML files that you intend to inject into your main HTML and then use template context using templateParameters to pass your HTML content. For example:
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const files = {
file1: fs.readFileSync('file1.html', { encoding: 'utf-8' }),
file2: fs.readFileSync('file1.html', { encoding: 'utf-8' })
};
module.exports = {
// ...other configuration
plugins: [
new HtmlWebpackPlugin({
title: 'Caching',
template: './src/template.html',
templateParameters: {
files
}
})
]
};
Your template.html file would be:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div><%= files.file1 %></div>
<div><%= files.file2 %></div>
</body>
</html>
The limitation here is that you can have includes only inside the template.html file. You cannot have recursive include like file2.html from file1.html. But this will work only if you intend to generate single HTML file.
Option 2
You can use the plugins for html-webpack-plugin. This plugin provides a nice support for partials. And, then there are few more plugins like this and this that can be used. Again these plugins will help you augment your generated html template and not support recursive include inside the html files.
Option 3
Using html-loader in combination extract-loader. This approach is flexible and can be used in multiple ways including using posthtml but it involves lots of configuration. You will have to write your own plugin in combination with other template loader that supports partials like handlebar-loader and then emit the HTML file.
Updates on comments
There are the two options you can try. First do not try to require the images inside the html partial. Instead add image using root relative paths like:
<-- partial.html --!>
<img src="/my/root/relative/image.png" />
The use Webpack copy plugin to copy the images into your dist folder.
I have not fully tried it but the second option is to disable the loader of html-webpack-plugin. Instead use html-loader with the plugin like below. By introducing the html-loader, the HTML file will be processed, the images would be picked up by the file-loader before the final HTML is seen by the html plugin.
const config = {
module: {
rules: [
{
test: /\.html$/,
loader: 'html-loader'
}],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};

ChildRoutes config not working anymore

So before this config use to work with react-router. But now I got a error message saying that; But I saw you need to use , but how to render the routes config insideReactDom.render( < div >
<Router history = {hashHistory}routes = {routes} > < /Router> </div>,
document.getElementById('react-app'));
?
routes.map is not a function
Can someone help me please.
const routes = {
component: Base,
childRoutes: [{
path: '/home',
getComponent: (location, callback) => {
if (Auth.isUserAuthenticated()) {
callback(null, Home);
} else {
callback(null, HomePage);
}
}
},
{
path: '/login',
component: LoginPage
},
]
}

Webpack is not copying images to dist folder

I'm starting with webpack, but I'm really new on this and I'm stuck right now.
My project copies my fonts correctly but not images. Now the only way I am able to make it work is by copying my images manually to the dist/img folder.
This is my config:
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require('webpack');
var path = require("path");
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname + '/dist'),
filename: 'app.bundle.js'
// publicPath: '/dist',
},
module: {
rules:[
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader?sourceMap","resolve-url-loader","sass-loader?sourceMap"],
// publicPath: '/dist'
})
},
{
test: /\.(woff2?|ttf|otf|eot|svg)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
// loader: 'file-loader?name=/fonts/[name].[ext]'
},
{
test: /\.(jpg|png|gif)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'img/',
publicPath:'img/'
}
}]
}
]
},
devServer: {
contentBase: path.join(__dirname, "/dist"),
compress: true,
port: 8000,
stats: "errors-only",
open: true
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new ExtractTextPlugin("styles.css"),
new HtmlWebpackPlugin({
title: 'Project',
hash:true,
template: './src/index.html'
})
]
}
I've tried several configurations but no solution. I also searched here for any solution but without success.
If your images are only referenced in HTML files as <img> tags, webpack by default won't pick them up because it doesn't parse HTML. You have at least 2 choices:
Use CopyWebpackPlugin to copy the files to wherever you want, this at least removes the "manual" part you mention
Move your images references to styles, where webpack can pick them up via the scss loader you are using. For example
background-image: url("img/foo.png");
There is also option import image trough JavaScript.
import '../img/image.png';
I had this problem. I didn't know that the file-loader only copies the images if you run a build, and doesn't do anything while using webpack-dev-server. My solution was just:
$ npx webpack

Webpack paths issue with es6

I have a structure like this but am having an error when trying to run webpack
/app
/main.js
/foo.js
/dist
index.html ( uses <script src="dist/bundle.js"></script>)
webpackconfig.js
in main.js:
import foo from './foo'
var foo = new foo()
foo.js:
export class foo {
constructor() {
loadScript("//www.parsecdn.com/js/parse-1.4.0.min.js", init());
}
}
webpackconfig.js
My config:
module.exports = {
context: __dirname + "/app",
entry: "./main.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
devtool: "#source-map",
module: {
loaders: [
// Transpile any JavaScript file:
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
]
},
resolve: {
// you can now require('file') instead of require('file.js')
extensions: ['', '.js', '.json']
}
}
but I get this error:
ERROR in ./main.js
Module not found: Error: Cannot resolve module 'foo'
It is because webpack try to load foo from node_modules directory.
You have to specify the path of your module like this:
import foo from './foo'