I have a React project with SASS using Webpack, my project compiles successfully, but does not represent the CSS effect in the HTML page in the browser. I compile it with webpack-dev-server command.
I have the following webpack.config.js:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
main: './src/scripts/main.js'
},
output: {
filename: './dist/scripts/[name].js'
},
devtool: 'source-map',
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css-loader!sass-loader')
}
]
},
plugins: [
new ExtractTextPlugin('dist/styles/main.css', {
allChunks: true
})
]
}
and following main.js:
import React from 'react';
import ReactDOM from 'react-dom';
import style from '../styles/main.scss';
ReactDOM.render(<h1 class="title">Hello World</h1>, document.getElementById('example'));
main.scss:
.example {
h1 {
color: green;
}
}
and this is the devDependcies section:
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.5",
"extract-text-webpack-plugin": "^3.0.0",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-hot-loader": "^1.3.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"webpack": "^3.1.0",
"webpack-dev-server": "^2.7.1"
}
Related
I've a problem with gulp and browserify. I want minify my index.js but he's import a figure.js with import 'swiper'. And Swiper contains "import" and "export" too.
My package.json
{
"name": "gulp-frontend-kit",
"version": "2.0.0",
"description": "Gulp boilerplate front-end dev Archriss",
"author": "Archriss",
"dependencies": {
"cookies-js": "^1.2.3",
"custom-event-polyfill": "^1.0.7",
"element-qsa-scope": "^1.0.1",
"html-truncate": "^1.2.2",
"lightgallery.js": "^1.0.1",
"node-fetch": "^3.2.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"swiper": "^8.2.2",
"tingle.js": "^0.16.0",
"tippy.js": "^6.3.7"
},
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.5",
"#babel/plugin-proposal-class-properties": "^7.17.12",
"#babel/plugin-transform-runtime": "^7.18.5",
"#babel/preset-env": "^7.18.2",
"#babel/preset-react": "^7.17.12",
"#babel/register": "^7.15.3",
"autoprefixer": "^10.4.7",
"babel-eslint": "^10.1.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babelify": "^10.0.0",
"browserify": "^17.0.0",
"css-mqpacker": "^7.0.0",
"cssnano": "^5.1.11",
"del": "^6.1.1",
"eslint": "^8.17.0",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-standard": "^5.0.0",
"gulp": "^4.0.0",
"gulp-buffer": "0.0.2",
"gulp-clean-css": "^4.3.0",
"gulp-combine-mq": "^0.4.0",
"gulp-concat": "^2.6.0",
"gulp-imagemin": "^7.1.0",
"gulp-livereload": "^4.0.2",
"gulp-postcss": "^9.0.1",
"gulp-sass": "^5.1.0",
"gulp-sourcemaps": "^3.0.0",
"gulp-stylelint": "^13.0.0",
"gulp-terser": "^2.1.0",
"gulp-uglify": "^3.0.2",
"gutil": "^1.6.4",
"imagemin-pngquant": "^9.0.2",
"node-sass": "^7.0.1",
"postcss-markdown": "^1.2.0",
"sass": "^1.52.3",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^2.0.0"
},
"scripts": {
"start": "gulp",
"watch": "gulp watch",
"build": "gulp build"
},
"browserify": {
"transform": [
[
"babelify",
{
"presets": [
"#babel/preset-env"
]
}
]
]
}
}
My .babelrc
{
"presets": [
"#babel/react" ,
"#babel/env" ,
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
My gulpfile.babel.js
const {src, dest, watch, series, parallel} = require('gulp'),
browserify = require('browserify'),
buffer = require('vinyl-buffer'),
concat = require('gulp-concat'),
livereload = require('gulp-livereload'),
source = require('vinyl-source-stream'),
sourcemaps = require('gulp-sourcemaps'),
uglify = require('gulp-uglify'),
babelify = require("babelify")
const FILENAMES = {jsCode: 'app.js', jsVendor: 'vendor.js'};
const PATHS = {
dest: {
global: './dist',
imgFolder: 'img',
prodFolder: 'prod',
devFolder: 'dev'
},
src: {
assets: ['src/assets/**', '!src/assets/{img,img/**}'],
html: 'src/html/*.html',
img: 'src/assets/img/**/*',
jsCode: ['src/js/**/*.js', '!src/js/{vendor,vendor/**}'],
jsEntry: 'src/js/index.js',
jsVendor: 'src/js/vendor/*.js',
scss: 'src/scss/**/*.scss'
}
};
function html() {
return src(PATHS.src.html).pipe(livereload());
}
function JSVendor(isDev) {
const targetFolder = isDev === true ? PATHS.dest.devFolder : PATHS.dest.prodFolder;
return src(PATHS.src.jsVendor)
.pipe(concat(FILENAMES.jsVendor))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(dest(PATHS.dest.global + '/' + targetFolder))
.pipe(livereload());
}
function JSCode(isDev) {
const targetFolder = isDev === true ? PATHS.dest.devFolder : PATHS.dest.prodFolder;
return (
browserify({
entries: [PATHS.src.jsEntry],
// Pass babelify as a transform and set its preset to #babel/preset-env
transform: [babelify.configure({presets: ["#babel/preset-env"]})]
})
// Bundle it all up!
.bundle()
// Source the bundle
.pipe(source("bundle.js"))
// Then write the resulting files to a folder
.pipe(dest(PATHS.dest.global + '/' + PATHS.dest.devFolder))
);
}
function catchJSErrors(err) {
if (err instanceof SyntaxError) {
console.log('Syntax Error');
console.log(err.message);
console.log(err.codeFrame);
} else {
console.log('Error', err.message);
}
this.emit('end');
}
exports.dev = function () {
const isDev = true;
watch(PATHS.src.html, html);
watch(PATHS.src.jsVendor, JSVendor(isDev));
watch(PATHS.src.jsCode, JSCode(isDev));
};
exports.build = function () {
const devOptions = {type: 'changed'};
};
exports.default = series(html);
And My error
$ gulp dev
[17:58:49] Requiring external module #babel/register
[17:58:50] Using gulpfile E:\docker\images\XXX\web\themes\custom\XXX\front\gulpfile.babel.js
[17:58:50] Starting 'dev'...
[17:58:51] 'dev' errored after 1.13 s
[17:58:51] Error:
E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\swiper\swiper.esm.js:13
export { default as Swiper, default } from './core/core.js';
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
at formatError (C:\Users\XXX\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\format-error.js:21:10)
at Gulp.<anonymous> (C:\Users\XXX\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\log\events.js:33:15)
at Gulp.emit (node:events:539:35)
at Gulp.emit (node:domain:475:12)
at Object.error (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\undertaker\lib\helpers\createExtensions.js:61:10)
at handler (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\now-and-later\lib\map.js:50:14)
at f (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\once\once.js:25:25)
at f (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\once\once.js:25:25)
at tryCatch (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\async-done\index.js:24:15)
at done (E:\docker\images\XXX\web\themes\custom\XXX\front\node_modules\async-done\index.js:40:12)
My versions :
npm -v : 8.12.1
node -v : v16.15.1
gulp -v : CLI : 2.3.0 - Local : 4.0.2
How fix this error ?
Try to add global: true
transform: [babelify.configure({global: true, presets: ["#babel/preset-env"]})]
I'm coding a Typescript application. In This application I'ld read some json file with the function d3.json, but the code doesn't work. The error is this:
SyntaxError: Unexpected token T in JSON at position 0
at JSON.parse ()
at Object. (d3-request.node.js:176)
at respond (d3-request.node.js:39)
at exports.XMLHttpRequest.onload.xhr.onreadystatechange (d3-request.node.js:30)
at exports.XMLHttpRequest.dispatchEvent (XMLHttpRequest.js:591)
at setState (XMLHttpRequest.js:610)
at exports.XMLHttpRequest.handleError (XMLHttpRequest.js:532)
at module.exports.errorHandler (XMLHttpRequest.js:459)
at module.exports.EventEmitter.emit (events.js:81)
at request.js:142
The code is this:
export async function setSelectConfiguration(
filenameJson: string, storeData: (str: string) => void, element: JQuery,
listenerFunction:(e: JQueryEventObject) => void) {
await d3.json("filename2.json", function(error, data) {
if(error) {
console.log(error);
} else {
console.log(data);
storeData(data.toString())
}
});
element.on("change", listenerFunction);
}
The json is this:
{
"files": [
{
"name": "time_sensitive_test.json",
"type": "user",
"owner": "Master",
"data_type": "linear data",
"description": "Utenti master (Enrica) periodo 20/05/2014-16/10/2014",
"ids_description": "accesso risorse",
"ods_description": "chat/forum",
"bds_description": "login/logout"
}
]}
the gulpfile.js:
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var tsify = require('tsify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
pages: ['src/*.html']
};
gulp.task('copyHtml', function () {
return gulp.src(paths.pages)
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['copyHtml'], function () {
return browserify({
basedir: '.',
debug: true,
entries: ['src/main.ts'],
cache: {},
packageCache: {}
})
.plugin(tsify)
.transform('babelify', {
presets: ['env','stage-0'],
extensions: ['.ts'],
plugins: ['transform-runtime','transform-async-to-generator']
})
.bundle()
.pipe(source('project.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
the package.json:
{
"name": "project",
"version": "1.0.0",
"description": " Project",
"main": "./dist/project.js",
"directories": {
"example": "example"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": " ... "
},
"author": " ",
"license": "ISC",
"bugs": {
"url": "... "
},
"homepage": "...",
"devDependencies": {
"#types/d3": "^4.10.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-0": "^6.24.1",
"babelify": "^8.0.0",
"browserify": "^14.5.0",
"gulp": "^3.9.1",
"gulp-sourcemaps": "^2.6.3",
"gulp-typescript": "^3.2.3",
"gulp-uglify": "^3.0.0",
"gulp-util": "^3.0.8",
"tsify": "^3.0.4",
"typescript": "^2.6.2",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0",
"watchify": "^3.9.0"
},
"dependencies": {
"#types/node": "^8.5.7",
"babel-polyfill": "^6.26.0",
"babel-runtime": "^6.26.0",
"d3": "^4.12.2",
"webpack": "^3.10.0"
}
}
the tsconfig.json:
{
"files": [
...
],
"compilerOptions": {
"module": "commonjs",
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"noImplicitAny": true,
"target": "es2015",
"lib": ["es2015", "es2016", "dom", "es2017", "es6", "es5"],
"experimentalAsyncFunctions": true,
"typeRoots": [
"./node_modules/#types"
]
},
"exclude": [
"node_modules",
"dist"
]
}
the webpack.config.json:
module.exports = {
context: __dirname + '/src',
entry: ['babel-polyfill', './main.ts'],
output: {
path: 'dist',
filename: 'project.js'
},
module: {
loaders: [
{
test: /\.js/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
}
};
I ran the code compiled outside the IDE, but the error appeared equally; so it should not be some strange fault of the IDE.
I've tried to read the file with in a pure javascript app and all works fine; so the problem is not to be found in the files.
What could be the problem? for example: does it need any special modules or configurations?
In my development environment I give
res.sendFile(path.resolve(__dirname,'../Views/setpwd.html');
and it is working well in development environment.
But in production Views are not moving to dist folder even though I have added html loader in webpack. Could you guys please help me on this?
Thanks in advance
## Webpack config##
var path = require('path');
var webpack=require('webpack');
var nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname,'dist'),
filename: 'src/server.js',
},
target: 'node',
externals: [nodeExternals()],
module: {
loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}],
loaders: [
{ test: /\.(html)$/, loader: "file" }
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
]
}
deVdependencies
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.5.1",
"babel-preset-es2015": "^6.24.1",
"file-loader": "^0.11.2",
"webpack": "^2.6.1",
"webpack-node-externals": "^1.6.0"
},
If I'm understanding this correctly, you want to copy over the HTML files in ../Views/*.html to a dist/ directory using webpack. If so, then you need to use the copy-webpack-plugin:
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../path/to/views/directory'),
to: path.resolve(__dirname, '../path/to/dist')
ignore: ['.*']
}
])
I have following problem. My webpack is bundling files from node_modules. How can I prevent him from doing that? He is doing that, because i import files from node_modules in main.ts, but i have to do this. What am i doing wrong?
main.ts
import { NgModule } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app/app.component';
#NgModule({
imports: [ BrowserModule ],
exports: [],
declarations: [AppComponent],
providers: [],
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
webpack.config.json
var webpack = require('webpack');
module.exports = {
entry : __dirname + '/src/main.ts',
output: {
path: __dirname + '/dist',
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader'
}
]
},
resolve: {
extensions: ['.js','.ts']
}
};
package.json
{
"name": "angular2",
"version": "1.0.0",
"scripts": {
"start": "webpack --progress"
},
"dependencies": {
"#angular/common": "~2.4.0",
"#angular/compiler": "~2.4.0",
"#angular/core": "~2.4.0",
"#angular/forms": "~2.4.0",
"#angular/http": "~2.4.0",
"#angular/platform-browser": "~2.4.0",
"#angular/platform-browser-dynamic": "~2.4.0",
"#angular/router": "~3.4.0",
"core-js": "^2.4.1",
"rxjs": "5.0.1",
"zone.js": "^0.7.4"
},
"devDependencies": {
"ts-loader": "^2.0.2",
"typescript": "^2.2.1",
"typings": "^2.1.0",
"webpack": "^2.3.0"
}
}
Test for .js files and exclude node modules in your loaders, example for using javascript(react) with babel-loader:
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: [
'es2015', 'react', 'stage-0',
],
}
},
In your main.js file you can just do import Module from 'module' where 'module' is the name of your component. Webpack will bundle it if you refer to it like that.
Example if I want to include React: import React from 'react' - no relative paths needed.
babel compile es6 about Uncaught SyntaxError: Unexpected token import.
I use webpack + gulp ,but throw Unexpected token import.How to solve this problem?
index.jsx
'use strict';
import React from 'react';
package.json
"devDependencies": {
"babel-core": "^6.3.15",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"gulp": "^3.9.0",
"gulp-webpack": "^1.5.0",
"react": "^0.14.3",
"react-tools": "^0.13.3",
"vinyl-named": "^1.1.0",
"webpack": "^1.12.9"
}
gulpfile.js
var gulp = require('gulp');
var webpack = require('gulp-webpack');
var named = require('vinyl-named');
gulp.task('dev', function() {
return gulp.src('app/scripts/index.jsx')
.pipe(named())
.pipe(webpack({
watch : true,
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}
]
},
output : {
filename : '[name].jsx',
},
resolve: {
alias: { localforage: 'localforage/dist/localforage.min' }
}
}))
.pipe(gulp.dest('app/dist/'));
});