Webpack - Javascript/Es6 - javascript

Just trying to run my app in Safari or Edge. http://ryanspice.com/test/
Unfortunately the console gives no errors, no compiling issues, and theres nothing signalling whats wrong. It seems to work perfectly in chrome and firefox.
Edit: From what I can tell the javascript is running
Here's my webpack.config.js
var path = require('path');
require("babel-core/register");
require("babel-polyfill");
var env = process.argv.indexOf('--env') === -1 ? false : true;
var spawn = require('child_process').spawn;
var source = {
input:{
js:'spice.js',
html:'./src/index.html',
path:'./src/',
},
output:{
js:"spice.js",
html:"../index.html"
}
}
var webpack = require('webpack');
var webpackPlugins = [];
if (env===true)
{
source.output.js = "spice.min.js";
var webpackUglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var webpackHtmlPlugin = require('html-webpack-plugin');
webpackPlugins.push(new webpackUglifyJsPlugin({ minimize: true }));
webpackPlugins.push(
new webpackHtmlPlugin({
filename: source.output.html, template:'./src/index.html'
})
);
}
module.exports = {
entry: ["babel-polyfill", source.input.path + source.input.js],
output: {
path: __dirname+"/bld/vendor",
filename: source.output.js
},
module: {
loaders: [
{
loader: "babel-loader",
include: [path.resolve(__dirname, "src")],
test: /\.jsx?$/
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
],
sassLoader: {
includePaths: [path.resolve(__dirname, "./css")]
}
},
plugins: webpackPlugins
};
Here's my .babelrc
{
"presets": ["es2015","stage-0"]
}

Related

Uncaught ReferenceError: __webpack_require__ is not defined Deploying to server

I am getting this error when logging into our dev site. This is a part of our migration from .NET framework 4.5.2 to 4.7.2. Though I do not think that has much to do with it. If we publish straight from VS, the page loads fine. If it uses our pipeline, or we did not clear our dirs beforehand, we get this error (in the console browser).
ie-polyfill_aurelia-bootstrapper:1 Uncaught ReferenceError:
webpack_require is not defined
at eval (ie-polyfill_aurelia-bootstrapper:1)
at Object.0 (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at t (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
The process of our build should be exactly the same as building with NPM locally, and there are no errors given in the build process. Build is defined for both in the webpack.config.js as follows
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { ProvidePlugin, SourceMapDevToolPlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');
const CleanWebpackPlugin = require('clean-webpack-plugin');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig)
// primary config:
const title = 'XXXXXX';
const outDir = path.resolve(__dirname, 'Scripts', 'pub');
const srcDir = path.resolve(__dirname, 'App');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
var isDevBuild = true;
var dev;
if (process.env.NODE_ENV) {
dev = process.env.NODE_ENV.trim();
if (dev === "production") {
isDevBuild = true;
}
}
const cssRules = [
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] }
},
'sass-loader'
];
module.exports = ({ production, server, extractCss, coverage } = {}) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: [srcDir, 'node_modules'],
plugins: [
new TsConfigPathsPlugin(),
],
alias: {
// Enforce single aurelia-binding, to avoid v1/v2 duplication due to
// out-of-date dependencies on 3rd party aurelia plugins
'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding'),
'aurelia-bootstrapper': path.resolve(__dirname, 'node_modules/aurelia-bootstrapper')
}
},
entry: {
app: ['./ie-polyfill', 'aurelia-bootstrapper'],
vendor: ['jquery'],
},
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js',
},
devServer: {
contentBase: baseUrl,
// serve index.html for all 404 (required for push-state)
historyApiFallback: '/',
},
module: {
rules: [
{
test: /\.css$/i,
issuer: [{ not: [{ test: /\.html$/i }] }],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules,
}) : ['style-loader', ...cssRules],
},
{
test: /\.css$/i,
issuer: [{ test: /\.html$/i }],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules,
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader']
})
},
{ test: /\.html$/i, loader: 'html-loader' },
{ test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
{
test: require.resolve("jquery"),
use: [
{
loader: "expose-loader",
options: "$"
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
// required polyfills for non-evergreen browsers
new ProvidePlugin({
Map: 'core-js/es6/map',
WeakMap: 'core-js/es6/weak-map',
Promise: 'core-js/es6/promise',
regeneratorRuntime: 'regenerator-runtime' // to support await/async syntax
}),
new AureliaPlugin({
aureliaApp: 'main'
}),
new ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
}),
new CheckerPlugin(),
new ExtractTextPlugin({
filename: production ? '[contenthash].css' : 'style-[id].css',
allChunks: true,
}),
].concat(isDevBuild ? [
new SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(outDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
new UglifyJsPlugin()
]),
})
There do seem to be a few times a similar question has been asked, but there has not been a solution that worked. Thanks for any help provided.

images not loading in html using webpack

I'm having any issue loading images from a different folder than where my index.html file is located. Below is the message I am getting from the console.
GET http://localhost:3000/company-logo.jpg 404 (Not Found)
Here is my file directory
webpack.config.js
const currentTask = process.env.npm_lifecycle_event
const path = require('path')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const fse = require('fs-extra')
const postCSSPlugins = [
require('postcss-import'),
require('postcss-simple-vars'),
require('postcss-nested'),
require('autoprefixer')
]
class RunAfterComile {
apply(compiler) {
compiler.hooks.done.tap('Copy images', function() {
fse.copySync('./public/images', './dist/public/images')
})
}
}
let cssConfig = {
test: /\.css$/i,
use: ['css-loader?url=false', {loader: 'postcss-loader', options: {plugins: postCSSPlugins}}]
}
let pages = fse.readdirSync('./views').filter(function(file) {
return file.endsWith('.html')
}).map(function(page) {
return new HtmlWebpackPlugin({
filename: page,
template: `./views/${page}`
})
})
let config = {
entry: './public/scripts/App.js',
plugins: pages,
module: {
rules: [
cssConfig
]
}
}
if (currentTask == 'dev') {
cssConfig.use.unshift('style-loader')
config.output = {
filename: 'bundled.js',
path: path.resolve(__dirname, 'public')
}
config.devServer = {
before: function(app, server) {
server._watch('./views/**/*.html')
},
contentBase: path.join(__dirname, './views'),
hot: true,
port: 3000
}
config.mode = 'development'
}
if (currentTask == 'build') {
config.module.rules.push({
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
})
cssConfig.use.unshift(MiniCssExtractPlugin.loader)
postCSSPlugins.push(require('cssnano'))
config.output = {
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist')
}
config.mode = 'production'
config.optimization = {
splitChunks: {chunks: 'all'}
}
config.plugins.push(
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({filename: 'styles.[chunkhash].css'}),
new RunAfterComile()
)
}
module.exports = config
The css works perfectly fine. I seem to only be having problems with images.
I tried the following file paths but they didn't work. I think I am missing something.
index.html
<img src="./company-logo.jpg" alt="dfgadfg">
<img src="../public/images/company-logo.jpg" alt="dfgadfg">
<img src="./images/company-logo.jpg" alt="dfgadfg">
any help would be appreciated. Thank you very much.
Try use
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
],
},
You might require file-loder to get the images correctly served
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
outputPath: 'images' // Chage this like 'public/images' or any other relative path to the root
}
},
...
]
Try to inspect and check how the images are loading in Source tab of Developer Tools, change the outputPath accordingly.
Update
If images are still not loading to Source tab of browser, try importing it in your App.js (Entry point file)
....
import "../public/images/company-logo.jpg";
...

webpack - output.filename error

I know this is a common question for webpack; it's really hard to debug something if it won't give you any information about the cause or location of the error.
I'm getting the error:
Error: 'output.filename' is required, either in config file or as --output-filename
I know it has to do with a syntax error somewhere, but I'm too new to webpack to figure it out.
Here's my config file. It's called "webpack.config.js" in the root folder (i.e. the folder in which I initially ran: npm init).
const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const RewriteImportPlugin = require("less-plugin-rewrite-import");
const root_dir = path.resolve(__dirname)
const src_dir = path.resolve(__dirname, "webpack_src")
const build_dir = path.resolve(__dirname, "webpack_bin")
const node_mod_dir = path.resolve(__dirname, 'node_modules');
const extractLESS = new ExtractTextPlugin('style.css');
const config = {
entry: {
index: path.resolve(src_dir, 'index.js')
},
output: {
path: build_dir,
filename: 'bundle.js'
},
resolve: {
modules: [root_dir, 'node_modules'],
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.(js)$/
},
{
use: extractLESS.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'less-loader',
options: {
paths: [root_dir, node_mod_dir],
plugins: [
new RewriteImportPlugin({
paths: {
'../../theme.config': __dirname + '/semantic_ui/theme.config',
}
})
]
}
}]
}),
test: /\.less$/
},
{
use: ['file-loader'],
test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/
},
]
},
plugins: [
extractLESS,
new webpack.optimize.ModuleConcatenationPlugin()
]
};
module.exports = {
config
};
You're exporting module.exports = { config }, which means that you are exporting an object with one property, namely config, but webpack expects the object to be your entire config. Webpack requires output.filename, whereas you only provide config.output.filename.
The export should be your config:
module.exports = config;

how to install reactjs npm package correctly

Hi I want to install this reactjs package called react-dropdown-input
https://github.com/RacingTadpole/react-dropdown-input/
I ran this command
$npm install react-dropdown-input --save
in my local folder in git bash. After that I checked my package.json, it says "react-dropdown-input": "^0.1.11" which means i have installed it correctly.
Then i tried to use it in my js file
import React from 'react'
import PropTypes from 'prop-types';
var DocumentTitle = require('react-document-title');
//var DropdownInput = require('react-dropdown-input');
When i added the fifth line, my page just could not load anymore (a blank page)
I dont know how to fix this.
Here's my webpack.config.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const path = require('path');
const webpack = require('webpack');
const BaseFolder = 'static/'; //relative to html path
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractLess = new ExtractTextPlugin({
filename: '[name].[contenthash].css',
disable: process.env.NODE_ENV === 'development'
});
var loaders = ['babel-loader'];
var port = process.env.PORT || 3000;
var vendor = ['react', 'react-dom', 'react-router', 'whatwg-fetch', 'es6-promise'];
var outputDir = 'dist';
var entry = {
filename: path.resolve(__dirname, 'src/app.js'),
}
var plugins = [
new webpack.optimize.CommonsChunkPlugin({
name:'vendor',
minChunks: Infinity,
filename: BaseFolder + 'js/[name].js',
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, '/src/index.html'),
filename: 'index.html',
inject: 'body'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'BaseFolder': JSON.stringify(BaseFolder)
}),
//new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
extractLess,
new webpack.ProvidePlugin({
Promise: 'es6-promise',
fetch: 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch',
React: 'react',
jsSHA: 'jssha',
wx: 'weixin-js-sdk'
}),
new CopyWebpackPlugin([
{
from: 'src/images',
to: BaseFolder + 'images'
}
])
];
if (process.env.NODE_ENV === 'development') {
//devtool ='eval-source-map';
loaders = ['react-hot-loader'].concat(loaders);
plugins = plugins.concat([
new webpack.HotModuleReplacementPlugin()
]);
entry = Object.keys(entry).reduce(function (result, key) {
result[key] = [
'webpack-dev-server/client?http://0.0.0.0:' + port,
'webpack/hot/only-dev-server',
entry[key]
];
return result;
}, {});
}
entry.vendor = vendor;
module.exports = env => {
return {
entry: entry,
output: {
filename: BaseFolder+'js/bundle.js',
chunkFilename: BaseFolder+'js/[id].chunk.js',
path: path.resolve(__dirname, outputDir),
publicPath: '/'
},
externals: [
],
module: {
loaders: [
{
test: /.jsx?$/,
loader: loaders,
exclude: /node_modules/,
include: __dirname
},
{ test: /\.js$/, exclude: /node_modules/, loaders: loaders, include: __dirname},
{ test: /\.scss$/, exclude: /node_modules/, loader: 'style-loader!css-loader?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap&includePaths[]=node_modules/compass-mixins/lib'},
{ test: /\.css$/, loader: 'style-loader!css-loader', exclude: /\.useable\.css$/},
{
test: /\.useable\.css$/,
use: [
{
loader: 'style-loader/useable'
},
{ loader: 'css-loader' },
],
},
{ test: /\.(png|jpg|jpeg|gif)$/, loader: 'url-loader?limit=100000&name='+BaseFolder+'images/[name].[ext]' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name='+BaseFolder+'fonts/[name].[ext]' },
{ test: /\.(woff|woff2)$/, loader:'url-loader?prefix=font/&limit=5000&name='+BaseFolder+'fonts/[name].[ext]' },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream&name='+BaseFolder+'fonts/[name].[ext]' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml&name='+BaseFolder+'images/[name].[ext]' },
]
},
plugins: plugins
}
};
Yes this must be included in your node_modules, but the point is that you have include that in your compiled js file or not, i.e.
you must have used webpack or gulp to compile all your dependencies of js to give one file and you must have forget to include that dependency file in webpack file or gulpfile, Please check or provide sample of your webpack or gulpfile.
I think that DropdownInput is named export from react-dropdown-input since in index.js file in the repository its exported as
module.exports = DropdownInput;
So need to import it like
import {DropdownInput} from 'react-dropdown-input'

Why is webpack creating output js in form of string and using eval function to deploy it?

My webpack.config.js file is as follows:
var path = require('path');
var webpack = require('webpack');
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';
module.exports = function makeWebpackConfig() {
var config = {};
if (isTest) {
config.devtool = 'inline-source-map';
} else if (isProd) {
config.devtool = 'source-map';
} else {
config.devtool = 'eval-source-map';
}
config.debug = !isProd || !isTest;
config.entry = isTest ? {} : {
'vendor': './src/vendor.ts',
'app': './src/bootstrap.ts' // our angular app
};
config.output = isTest ? {} : {
path: root('../edu_analytics_prod_front/dist'),
publicPath: isProd ? '/' : '/',
filename: isProd ? 'js/[name].[hash].js' : 'js/[name].js',
chunkFilename: isProd ? '[id].[hash].chunk.js' : '[id].chunk.js'
};
config.resolve = {
cache: !isTest,
root: root(),
extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html'],
alias: {
'app': 'src/client',
'common': 'src/common'
}
};
config.module = {
preLoaders: isTest ? [] : [{test: /\.ts$/, loader: 'tslint'}],
loaders: [
// Support for .ts files.
{
test: /\.ts$/,
loader: 'ts',
query: {
'ignoreDiagnostics': [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 -> Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375, // 2375 -> Duplicate string index signature
2502 // 2502 -> Referenced directly or indirectly
]
},
exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
},
{test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: 'file?name=fonts/[name].[hash].[ext]?'},
{test: /\.json$/, loader: 'json'},
{
test: /\.css$/,
exclude: root('src', 'client'),
loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
},
// all css required in src/client files will be merged in js files
{test: /\.css$/, include: root('src', 'client'), loader: 'raw!postcss'},
{
test: /\.scss$/,
exclude: root('src', 'client'),
loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass')
},
{test: /\.scss$/, exclude: root('src', 'style'), loader: 'raw!postcss!sass'},
{test: /\.html$/, loader: 'raw'}
],
postLoaders: [],
noParse: [/.+angular2\/bundles\/.+/]
};
if (isTest) {
config.module.postLoaders.push({
test: /\.(js|ts)$/,
include: path.resolve('src'),
loader: 'istanbul-instrumenter-loader',
exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
})
}
config.plugins = [
new webpack.DefinePlugin({
'process.env': {
ENV: JSON.stringify(ENV)
}
})
];
if (!isTest) {
config.plugins.push(
new CommonsChunkPlugin({
name: ['vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: './src/public/index.html',
inject: 'body',
chunksSortMode: packageSort(['polyfills', 'vendor', 'app'])
}),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
}),
new ExtractTextPlugin('css/[name].[hash].css', {disable: !isProd})
);
}
if (isProd) {
config.plugins.push(
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
}),
new CopyWebpackPlugin([{
from: root('src/public')
}])
);
}
config.postcss = [
autoprefixer({
browsers: ['last 2 version']
})
];
config.sassLoader = {
//includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
};
config.tslint = {
emitErrors: false,
failOnHint: false
};
config.devServer = {
contentBase: './src/public',
historyApiFallback: true,
stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
};
return config;
}();
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
args = Array.prototype.slice.call(arguments, 0);
return root.apply(path, ['node_modules'].concat(args));
}
function packageSort(packages) {
var len = packages.length - 1;
var first = packages[0];
var last = packages[len];
return function sort(a, b) {
if (a.names[0] === first) {
return -1;
}
if (a.names[0] === last) {
return 1;
}
if (a.names[0] !== first && b.names[0] === last) {
return -1;
} else {
return 1;
}
}
}
When I'm running command like webpack / webpack -p
It is creating three files as follows:
But all three files has output as string and using eval function to deploy it and one file has very big size(7 MB) as follows.
I want simple JavaScript file without eval used inside it as all other common minification library works and I want to reduce size of vendor file as well.
Your config uses this configuration as default:
config.devtool = 'eval-source-map';
The fine manual states:
eval-source-map - Each module is executed with eval and a SourceMap is added as DataUrl to the eval.
If you don't want that, use another devtool option.
As for decreasing code size, you probably want to either disable the creation of a source map entirely (just don't set the devtool option) or have Webpack write the source map to a separate file (devtool : 'source-map' or devtool : 'cheap-source-map', AFAIK).
Also set the NODE_ENV environment variable to production if you want less code:
# if you're on a Unix-like OS:
env NODE_ENV=production webpack -p

Categories