Javascript es6 class is not defined - javascript

After building my project it gives me this error but in the console of chrome it gives me the following error. Could someone help me? I have no idea what causes this. It feels like im using export and class in a wrong way.
Node version: v11.6.0
Npm version: 4.6.1
webpack.config.js
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
module.exports = {
entry:
{
widget: ['./src/js/widget/v1/widget.js', './src/sass/widget/widget.scss'],
website: ['./src/sass/website/website.scss', './src/js/website/website.js']
},
output: {
path: path.resolve(__dirname, 'static'),
filename: '[name]/[name].js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
enforce: 'pre',
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
},
},
{
test: /\.(css|scss)$/,
loaders: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader?minimize!sass-loader'],
}),
},
{
test: /\.(scss)$/,
loader: "sass-loader", // compiles Sass to CSS
options: {
data: "$HOST-URL: '" + "localhost:8000" + "';"
}
},
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=image/svg+xml' },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=application/font-woff' },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=application/font-woff' },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=application/octet-stream' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader' },
],
},
stats: {
colors: true,
},
devtool: 'source-map',
plugins: [
new webpack.DefinePlugin({
HOST_URL: "localhost:8000"
}),
new CopyWebpackPlugin([
{ from: './node_modules/font-awesome/fonts/', to: './assets/fonts/' },
{ from: './src/widget/', to: './widget/' },
{ from: './src/website/', to: './website/' },
]),
new StyleLintPlugin(),
new ExtractTextPlugin({
filename: '[name]/css/[name].css',
allChunks: true,
}),
new UglifyJSPlugin(),
],
};
package.json
{
"name": "name",
"version": "0.0.1",
"main": "index.js",
"author": "author",
"license": "MIT",
"devDependencies": {
"autoprefixer": "^6.7.7",
"babel-core": "^6.26.3",
"babel-eslint": "^7.1.1",
"babel-loader": "^6.4.0",
"babel-preset-es2015": "^6.22.0",
"css-loader": "^0.26.4",
"eslint": "^3.17.1",
"eslint-config-airbnb": "^14.1.0",
"eslint-loader": "^1.6.3",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.10.0",
"file-loader": "^0.10.1",
"http-server": "^0.11.1",
"node-sass": "^4.9.2",
"postcss-loader": "^1.3.3",
"sass-loader": "^6.0.3",
"style-loader": "^0.13.2",
"stylelint-config-standard": "^16.0.0",
"stylelint-webpack-plugin": "^0.7.0",
"uglifyjs-webpack-plugin": "^0.3.0",
"webpack": "^2.7.0",
"webpack-shell-plugin": "^0.5.0"
},
"scripts": {
"babel": "babel --presets es2015 js/main.js -o build/main.bundle.js",
"webpack": "webpack",
"watch": "webpack --watch"
},
"dependencies": {
"bootstrap": "^4.0.0",
"bootstrap-datepicker": "^1.6.4",
"bootstrap-sass": "^3.3.7",
"copy-webpack-plugin": "^4.5.2",
"extract-text-webpack-plugin": "^2.1.0",
"font-awesome": "^4.7.0",
"formdata-polyfill": "^3.0.9",
"jquery": "^3.2.1",
"popper.js": "^1.12.9"
}
}
widget.js
import Video from './video';
import Overlay from './overlay';
class Widget {
...
}
export {Widget as default}
window.Widget = Widget;
Video and Overlay are also classes and exported the same way as the Widget class. Before this, it was declares as
export default class Widget{}
The code where I am trying to access Widget is in the index.html, where I create a new Widget inside the script tag.
index.html
<script type="text/javascript">
var widget = new Widget({
});
widget.render();
</script>

Related

JSX causing Errors with Jest and Enzyme

When I run the code below I get a repeated error trying to use enzyme with jest on the first JSX component <. So far, I haven't been able to find anything on this occurring with React and not React-Native. So I have followed many tutorials I have found, listened to all the advice, but to no avail.
What could the problem be? Sorry for so much code, but it is all needed for context.
Dependencies:
"dependencies": {
"#babel/core": "^7.8.3",
"#babel/plugin-proposal-class-properties": "^7.8.3",
"#babel/preset-env": "^7.8.3",
"#babel/preset-react": "^7.8.3",
"autoprefixer": "^9.7.4",
"babel-jest": "^25.1.0",
"babel-loader": "^8.0.6",
"css-loader": "^3.4.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"eslint": "^6.8.0",
"eslint-config-jest-enzyme": "^7.1.2",
"eslint-plugin-jest": "^23.7.0",
"jest": "^25.1.0",
"mini-css-extract-plugin": "^0.9.0",
"moment": "^2.24.0",
"postcss-loader": "^3.0.0",
"postcss-nested": "^4.2.1",
"puppeteer": "^2.1.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-highlighter": "^0.4.3",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-test-renderer": "^16.12.0",
"redux": "^4.0.5",
"style-loader": "^1.1.3",
"tailwindcss": "^1.1.4",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
},
"devDependencies": {
"babel-eslint": "^10.0.3",
"eslint": "^6.1.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-loader": "^3.0.3",
"eslint-plugin-import": "^2.20.0",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.18.0",
"eslint-plugin-react-hooks": "^1.7.0",
"webpack-dev-server": "^3.10.1",
"write-file-webpack-plugin": "^4.5.1"
}
Test:
{
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Button from '../src/components/utility/Button';
Enzyme.configure({ adapter: new Adapter() });
describe('<Button /> Testing', () => {
it('renders Button without crashing', () => shallow(<Button />));
});
}
webpack.config.js:
const path = require('path');
const { HotModuleReplacementPlugin } = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const WriteFilePlugin = require('write-file-webpack-plugin');
module.exports = (env, argv) => ({
entry: ['#babel/polyfill', path.join(__dirname, 'src', 'index.js')],
plugins: [
new MiniCssExtractPlugin({
filename: '[name].bundle.css',
chunkFilename: '[id].css',
}),
new WriteFilePlugin({
// Write only files that have ".css" extension.
test: /\.css$/,
useHashIndex: true,
}),
new HotModuleReplacementPlugin(),
],
devServer: {
open: true,
clientLogLevel: 'silent',
contentBase: './dist',
historyApiFallback: true,
hot: true,
},
module: {
rules: [
{
test: /\.(jsx|js)$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-env', {
targets: {
node: '10',
},
}],
'#babel/preset-react',
],
plugins: ['#babel/plugin-proposal-class-properties'],
},
}, {
loader: 'eslint-loader',
options: {
fix: true,
},
}],
},
{
test: /\.css$/i,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: [
'style-loader',
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: argv.mode === 'development',
},
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
'postcss-loader',
],
},
],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
});
I ended up figuring out what the issue was. We didn't have our babel setup in a way that Enzyme would use it. This can be done through a .babelrc file which in hindsight is probably better to use. At present I resolved it by adding configuration for babel into the package.json. I'm sure there's a better way to do this, probably with a .babelrc since Enzyme looks for that by default from what I could find.
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-runtime"
]
},

ERROR in ./node_modules/bootstrap-loader/no-op.js

I'm using Webpack in my application, in which I create my entry point as
index.ts and I'm trying to run it using sass css bootstrap typescript as resources in my project webpack, but I am stuck with these errors,(bootstrap-loader) :
ERROR in ./node_modules/bootstrap-loader/no-op.js
(./node_modules/bootstrap-loader/lib/bootstrap.scripts.loader.js?{"bootstrapVersion":3,"useCustomIconFontPath":false,"extractStyles":false,"styleLoaders":["style-loader","css-loader","sass-loader"],"styles":["mixins","normalize","print","glyphicons","s
caffolding","type","code","grid","tables","forms","buttons","component-animations","dropdowns","button-groups","input-groups","navs","navbar","breadcrumbs","pagination","pager","labels","badges","jumbotron","thumbnails","alerts","progress-bars","media","list-group","panels","wells","responsive-embed","close","modals","tooltip","popovers","carousel","utilities","responsive-utilities"],"scripts":["transition","alert","button","carousel","collapse","dropdown","modal","tooltip","popover","scrollspy","tab","affix"],"configFilePath":"/projects/bootstrapwebpack/node_modules/bootstrap-loader/.bootstraprc-3-default","bootstrapPath":"/projects/bootstrapwebpack/node_modules/bootstrap-sass","bootstrapRelPath":"../bootstrap-sass"}!./node_modules/bootstrap-loader/no-op.js)
...
In my config.js I have :
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: [ 'bootstrap-loader', './src/index.ts',],
module: {
rules:[
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
],
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
},
},
],
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
exclude: /node_modules/
},
// Boooootstrap
{
test: /bootstrap-sass\/assets\/javascripts\//,
loader: 'imports-loader?jQuery=jquery'
},
{
test: /\.(woff2?|svg)$/, loader: 'url-loader?limit=10000'
},
{
test: /\.(ttf|eot)$/, loader: 'file-loader'
},
],
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
Currently I'm trying to use in my package.json these following lines :
{
"name": "test",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "webpack --mode development --watch ",
"build": "webpack --progress -p --watch "
},
"dependencies": {
"autoprefixer": "^9.0.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"bootstrap": "^4.1.2",
"bootstrap-loader": "^3.0.0",
"bootstrap-sass": "^3.3.7",
"css-loader": "^1.0.0",
"exports-loader": "^0.7.0",
"file-loader": "^1.1.11",
"image-webpack-loader": "^4.3.1",
"jquery": "^3.3.1",
"mini-css-extract-plugin": "^0.4.1",
"node-sass": "^4.9.2",
"popper.js": "^1.14.3",
"postcss-loader": "^2.1.6",
"resolve-url-loader": "^2.3.0",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"ts-loader": "^4.4.2",
"typescript": "^2.9.2",
"url-loader": "^1.0.1",
"webpack": "^4.16.0",
"webpack-cli": "^3.0.8"
}
}
I had the same problem yesterday.
Try adding in ./src/index.ts
require 'bootstrap/dist/css/bootstrap.min.css';
require 'bootstrap/dist/js/bootstrap.min.js';

Webpack, Gulp, and React loading errors

My setup is below. If I run gulp in the directory with these files, then I get a boatload of errors that look like the following. They all have a similar signature but are failing to find a different part of react-bootstrap, react-dom, or the like.
Module not found: Error: Can't resolve 'react-bootstrap/lib/Input' in '...a/scripts/components'
# ./a/scripts/components/SearchBar.js 7:12-48
# ./a/scripts/pages/HomePage.js
# ./a/scripts/routes.js
# ./a/scripts/index.js
# multi webpack-dev-server/client?http://localhost:8083 webpack/hot/only-dev-server ./a/scripts/index
This makes me think it's to do with the loader. And in fact, if I run npm install, then after verifying that everything is installed and making a bundle.js, this error occurs:
ERROR in ./a/scripts/index.js
Module parse failed: Unexpected token (19:15)
You may need an appropriate loader to handle this file type.
|
| Router.run(routes, Router.HistoryLocation, function(Handler) {
| React.render(<Handler />, document.getElementById('entry'));
| });
|
# multi ./a/scripts/index
Which also suggests it's with the loader. I've since spent a lot of time trying to figure out why the loader wouldn't be working and am coming up blank. Help would be greatly appreciated.
package.json
{
"version": "1.0.0",
"main": "index.js",
"engines": {
"node": "0.12.7",
"npm": "2.7.5"
},
"scripts": {
"postinstall": "gulp build"
},
"author": "",
"license": "none",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"css-loader": "^0.28.8",
"del": "^3.0.0",
"file-loader": "^1.1.6",
"gulp": "^3.9.1",
"gulp-autoprefixer": "^4.1.0",
"gulp-cache": "^1.0.2",
"gulp-clean-css": "^3.9.2",
"gulp-concat": "^2.5.2",
"gulp-imagemin": "^4.1.0",
"gulp-jshint": "^2.1.0",
"gulp-livereload": "^3.8.0",
"gulp-notify": "^3.1.0",
"gulp-rename": "^1.2.0",
"gulp-ruby-sass": "^3.0.0",
"gulp-uglify": "^3.0.0",
"jsx": "^0.9.89",
"jsx-loader": "^0.13.2",
"lodash": "^4.17.4",
"moment": "^2.9.0",
"node-sass": "^4.7.2",
"plugin-error": "^0.1.2",
"react": "^16.2.0",
"react-bootstrap": "^0.32.0",
"react-hot-loader": "^3.1.3",
"react-router": "^4.2.0",
"react-script-loader": "^0.0.1",
"run-sequence": "^2.2.1",
"sass-loader": "^6.0.6",
"sass-material-colors": "0.0.5",
"style-loader": "^0.19.1",
"superagent": "^3.8.2",
"underscore": "^1.8.3",
"url-loader": "^0.6.2",
"webpack": "^3.10.0",
"webpack-dev-server": "2.10.1"
},
"dependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1"
},
}
.babelrc
{
"presets": ["env", "react"]
}
gulpfile.babel.js
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
autoprefixer = require('gulp-autoprefixer'),
cleanCSS = require('gulp-clean-css'),
rename = require('gulp-rename');
var log = require('fancy-log');
var PluginError = require('plugin-error');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackConfig = require("./webpack.config.js");
var runSequence = require('run-sequence');
var path = require('path');
var del = require('del');
var watch = true;
var verbose = true;
// Default to Dev Server
gulp.task('default', ["js-dev-server"]);
// Clean output directory
gulp.task('clean', () => del(['a/static/js/build/*', 'a/static/css/*'], {dot:true}))
gulp.task('styles', function() {
return sass('a/static/scss/styles.scss', { style: 'expanded' })
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
.pipe(gulp.dest('a/static/css'))
.pipe(rename({suffix: '.min'}))
.pipe(cleanCSS())
.pipe(gulp.dest('a/static/css'));
});
gulp.task('watch', function() {
gulp.watch('a/static/scss/**/*.scss', ['styles']);
});
gulp.task('bundle', function() {
function bundle(err, stats) {
if (err) {
throw new PluginError("build", err);
}
console.log(stats.toString({
colors: true,
hash: verbose,
version: verbose,
timings: verbose,
chunks: verbose,
chunkModules: verbose,
cached: verbose,
cachedAssets: verbose
}));
}
webpack(webpackConfig).run(bundle)
});
gulp.task('build', ['clean'], cb => { runSequence(['styles', 'bundle']); });
gulp.task("js-dev-server", function(callback){
// modify some webpack config options
var myConfig = Object.create(webpackConfig);
myConfig.devtool = "eval-source-map";
myConfig.entry = [
'webpack-dev-server/client?http://localhost:8083',
'webpack/hot/only-dev-server',
'./a/scripts/index'
];
myConfig.plugins = [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.LoaderOptionsPlugin({debug: true})
];
myConfig.output['publicPath'] = "http://localhost:8083/static/js/build/"
myConfig.module = {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot-loader/webpack', 'jsx-loader?harmony', 'babel-loader']
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=a/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&minetype=image/svg+xml" },
{ test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]=" +
path.resolve(__dirname, "./a/static/scss/")
}
]
};
// Start a webpack-dev-server
new WebpackDevServer(webpack(myConfig), {
publicPath: "http://localhost:8083/static/js/build/",
stats: {
colors: true
},
inline: true,
hot: true,
historyApiFallback: true,
contentBase: 'http://localhost:5000/'
}).listen(8083, "localhost", function(err) {
if(err) throw new PluginError("webpack-dev-server", err);
log("[webpack-dev-server]",
"http://localhost:8083/webpack-dev-server/index.html");
});
});
webpack.config.js
var webpack = require('webpack');
var path = require('path');
var DEBUG = true;
module.exports = {
entry: [
__dirname + '/a/scripts/index'
],
output: {
path: __dirname + '/a/static/js/build',
filename: 'bundle.js',
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({sourceMap: false,
output: {comments: false}}),
],
resolve: {
extensions: ['.js', '.jsx'],
modules: ['node_modules', 'web_modules', 'scripts', 'lib'],
},
module: {
rules: [
{
test: /\*.js.x?$/,
exclude: /node_modules/,
loaders: (DEBUG ? ['react-hot-loader/webpack'] : []).concat(['babel-loader'])
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&minetype=image/svg+xml" },
{ test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]=" +
path.resolve(__dirname, "./a/static/scss/")
}
]
},
externals: {
"jquery": "jQuery"
}
};
index.js
'use strict';
var React = require('react'),
Router = require('react-router'),
routes = require('routes');
// set up in order to receive actions
var NotificationStore = require('stores/NotificationStore');
require('csrf'); // injects CSRF token into all $.ajax calls
require('../static/scss/playground.scss'); // loads stylesheet into JS
Router.run(routes, Router.HistoryLocation, function(Handler) {
React.render(<Handler />, document.getElementById('entry'));
});
This issue is due to your babel setup. You need to install babel-plugin-transform-react-jsx and adjust your .babelrc file. Like this:
{
"presets": ["env", "es2015", "react"],
"plugins": ["transform-react-jsx", "transform-object-rest-spread"]
}
example webpack.config.js:
const path = require('path')
const config = {
entry: {
app: ['whatwg-fetch','./src/index.js'],
},
devtool: 'inline-source-map',
devServer: {
contentBase: './public'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
},
{
test: /\.css/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
]
},
output: {
filename: 'app.bundle.js',
path: path.resolve(__dirname, 'public')
}
}
module.exports = config
example package.json:
{
"name": "react-news-app",
"version": "1.0.0",
"description": "get news and sentiment from headline articles",
"main": "index.js",
"scripts": {
"test": "jest --watch",
"start": "webpack-dev-server --port 3000"
},
"keywords": [
"api",
"react"
],
"author": "Stephen Collins",
"license": "MIT",
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"whatwg-fetch": "^2.0.3"
},
"devDependencies": {
"babel-jest": "^22.0.4",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.6.1",
"chai": "^4.1.2",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.8",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^4.15.0",
"eslint-loader": "^1.9.0",
"jest": "^22.0.4",
"prop-types": "^15.6.0",
"sinon": "^4.1.3",
"style-loader": "^0.19.1",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.10.0"
}
}

[webpack2]Style not loaded(.css/.less)

I'm currently working on a webpack2 + react + antd-mobile application, everything's working except styles not loaded(.css/.less). I can't really find the problem, there are no error printed on the console.
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const pxtorem = require('postcss-pxtorem');
// antd-mobile SVG配置方式
const svgDirs = [
require.resolve('antd-mobile').replace(/warn\.js$/, ''),
path.resolve(__dirname, 'src/assets/svg'),
];
module.exports = {
devtool: 'source-map',
context: path.join(__dirname, 'src'),
entry: './index',
output: {
filename: '[hash].js',
},
resolve: {
modules: ['node_modules', path.join(__dirname, 'src')],
extensions: ['.web.js', '.js', '.json', '.less', '.css'],
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(css|less)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'postcss-loader', 'less-loader'],
}),
},
{
test: /\.html$/,
loader: 'html-loader',
},
{
test: /\.(svg)$/i,
use: 'svg-sprite-loader',
include: svgDirs,
},
],
},
plugins: [
new ExtractTextPlugin('main.css'),
new HtmlWebpackPlugin({
template: 'index.html',
hash: true,
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.NODE_ENV === 'development' || 'true')),
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: () => {
return [
pxtorem({ rootValue: 100, propWhiteList: [] }),
autoprefixer,
];
},
},
}),
],
};
I can import less in but style is not loaded and no error output shown on the console;
import styles from './styles/AssetItem.less';
package.json
{
"private": true,
"scripts": {
"start": "cross-env NODE_ENV=development webpack-dev-server --hot --port 8000",
"build": "webpack -p --progress --colors",
"lint": "eslint --ext .js src test"
},
"dependencies": {
"antd-mobile": "^1.1.0",
"lodash": "^4.17.4",
"moment": "^2.18.1",
"react": "15.4.2",
"react-dom": "15.4.2",
"react-native": "0.42.3",
"react-redux": "^5.0.4",
"react-router": "^4.1.1",
"react-router-redux": "^4.0.8",
"redux": "^3.6.0",
"redux-saga": "^0.14.8",
"regenerator-runtime": "^0.10.3"
},
"devDependencies": {
"autoprefixer": "^6.7.7",
"babel-core": "^6.24.1",
"babel-eslint": "^7.2.3",
"babel-loader": "^7.0.0",
"babel-plugin-import": "^1.1.1",
"babel-plugin-react-transform": "^2.0.2",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"cross-env": "^4.0.0",
"css-loader": "^0.28.0",
"eslint": "^3.19.0",
"eslint-config-airbnb": "^14.1.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-jsx-a11y": "^4.0.0",
"eslint-plugin-react": "^6.10.3",
"extract-text-webpack-plugin": "^2.1.0",
"html-loader": "^0.4.5",
"html-webpack-plugin": "^2.28.0",
"less": "^2.7.2",
"less-loader": "^4.0.3",
"postcss": "^5.2.17",
"postcss-loader": "^1.3.3",
"postcss-pxtorem": "^4.0.0",
"react-transform-catch-errors": "^1.0.2",
"react-transform-hmr": "^1.0.4",
"redbox-react": "^1.3.6",
"style-loader": "^0.16.1",
"svg-sprite-loader": "^0.3.1",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.5"
}
}
I don't know if it can help you but there my part to resolve css file with webpack2
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
modules: false
}
}
]
},
this should work:
module: {
rules: [
{
test: /.js$/,
use: [
{ loader: 'babel-loader' }
],
},
{
test: /(\.css|\.less)$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: "css-loader!less-loader",
}),
},
],
},
plugins: [
new ExtractTextPlugin('main.css'),
],
I think, the problem is that you forgot about new ExtractTextPlugin syntax, more information you can read here: https://webpack.js.org/guides/migrating/#extracttextplugin-extract
plugins: [
new ExtractTextPlugin({
filename: "main.css"
})
You should add path for output files
output: {
filename: '[hash].js',
path: path.resolve(__dirname, 'public'),
},

Can't export reducer with Babel

This is most likely some typo but I've been trying to fix it for the last hour and came up with nothing.
I have a file called app/reducers/index.js:
export viewportSize from "./viewportSize";
app/reducers/viewportSize.js is simply:
export default function viewportSize (state = {}) {
return state;
}
And in app/app.js I do:
import reducers from "./reducers";
Babel is giving me back this error
ERROR in ./app/reducers/index.js
1:8 error Parsing error: Unexpected token viewportSize
I have other import and export in the project but this one doesn't want to work.
This is my .babelrc file:
{
"presets": ["es2015", "react", "stage-2"]
}
Update
These are my dependencies
"devDependencies": {
"babel-core": "6.5.2",
"babel-loader": "6.2.3",
"babel-preset-es2015": "6.5.0",
"babel-preset-react": "6.5.0",
"babel-preset-stage-2": "6.5.0",
"eslint": "2.2.0",
"eslint-loader": "1.3.0",
"eslint-plugin-react": "4.1.0",
"file-loader": "0.8.5",
"react-hot-loader": "1.3.0",
"webpack": "1.12.14",
"webpack-dev-server": "1.14.1"
},
"dependencies": {
"babel-preset-stage-0": "6.5.0",
"immutable": "3.7.6",
"react": "0.14.7",
"react-dom": "0.14.7",
"react-redux": "4.4.0",
"react-router": "2.0.0",
"react-router-redux": "4.0.0",
"redux": "3.3.1"
}
Update
This is my webpack config file
var webpack = require("webpack");
module.exports = {
context: __dirname + "/app",
entry: {
javascript: "./app.js",
html: "./index.html",
css: "./style.css",
},
output: {
filename: "app.js",
path: __dirname + "/dist",
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
include: __dirname,
loaders: ["react-hot", "babel-loader", "eslint-loader"],
},
{
test: /\.html$/,
loader: "file?name=[name].[ext]",
},
{
test: /\.css$/,
loader: "file?name=[name].[ext]",
},
],
},
};

Categories

Resources