webpack - output.filename error - javascript

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;

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.

Webpack adds "auto/" to script tags in the built html file

So, I'm trying to get this application setup so I can start coding it. But everytime I build the application; webpack automatically adds auto/file.js to the script tags, but it should really be: file.js. So it's adding the auto/ part by itself. I've checked every webpack config file, and I cannot understand why it adds the auto/ prefix to my scripts.
Also like to mention this is a ElectronJS project.
Here are my configurations for webpack.
webpack.config.js
const mainConfig = require("./webpack.main.config");
const rendererConfig = require("./webpack.renderer.config");
const config = [mainConfig, rendererConfig];
module.exports = config;
webpack.base.config.js
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const config = {
plugins: [
new UglifyJsPlugin({
test: /\.js($|\?)/i,
sourceMap: true,
uglifyOptions: {
compress: true
}
})
]
};
module.exports = config;
webpack.main.config.js
const path = require("path");
const merge = require("webpack-merge");
const base = require("./webpack.base.config");
const buildPath = path.resolve(__dirname, "./dist");
const main = merge(base, {
entry: "./main.js",
output: {
filename: "main.js",
path: buildPath
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
},
]
},
node: {
__dirname: false,
__filename: false
},
target: "electron-main"
});
module.exports = main;
webpack.renderer.config.js (this is where i think the problem is happening)
const path = require("path");
const merge = require("webpack-merge");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const base = require("./webpack.base.config");
const buildPath = path.resolve(__dirname, "./dist");
const renderer = merge(base, {
entry: "./src/renderer.js",
output: {
filename: "renderer.js",
path: buildPath
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html"
})
],
target: "electron-renderer",
});
module.exports = renderer;
And after the build, when I open the index.html file from the dist directory, the script tag is like this: <script src="auto/renderer.js"></script> when it should just be <script src="renderer.js"></script>
What could be causing this? Is there any configuration I am missing here?
Thanks in advance!
Solved it by updating webpack.

How to limit scope of webpack

I'm currently trying to implement typescript into my backend, but since it's quite new to me, I'm trying to figure things out one by one in a test folder, however it seems like webpack is taking all of my files and trying to read them, which gives me errors like:
Duplicate identifier, Module '"xxxx"' has no default export, Cannot find name 'Proxy'., Cannot redeclare block-scoped variable 'xxxx'.
Here's my config file (still using webpack3 for reasons):
"use strict"
const path = require("path")
// const utils = require("./utils")
// const config = require("../config")
var fs = require("fs")
const NodemonPlugin = require("nodemon-webpack-plugin")
const nodeExternals = require("webpack-node-externals")
function resolve(dir)
{
return path.join(__dirname, "..", dir)
}
module.exports = {
context: path.resolve(__dirname, "../src/server/test"),
entry: "./test.ts",
output: {
path: path.resolve(__dirname, "../src/server/test"),
filename: "bundle.js",
},
plugins: [
// new NodemonPlugin(),
],
resolve: {
extensions: [".js",".ts", ".tsx"],
alias: {
"#": resolve("src"),
"#": resolve("src/server")
}
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: [resolve("src"), resolve("test")]
},
{
test: /\.tsx?$/,
loader: "ts-loader",
},
]
},
externals: [
nodeExternals()
],
target: "node"
}

Issue with weakmap.get on IE11

I have a class using WeakMaps as follows
const myWeakMap = new WeakMap();
class myClass {
constructor(myObject) {
myWeakMap.set(this, myObject);
}
getProperty () {
return myWeakMap.get(this).property;
}
}
var instance = new myClass({property: 5});
console.log(instance.getProperty());
This works fine when using chrome, firefox, but on IE this throws a cannot read property 'property' of undefined error because myWeakMap.get(this) is undefined. Also when I use the production build property of Webpack that only does a uglify of the code the system works properly on IE. I am not sure what is different or what causes the issue and not sure how to debug the issue. Any help would be welcome.
Webpack configuration
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const BUILD_DIR_CLIENT = path.resolve(__dirname, "build-client");
const APP_DIR = path.resolve(__dirname, "src/client/main");
const SHARED_DIR = path.resolve(__dirname, "src/shared");
const extractCSS = new ExtractTextPlugin("main.css");
const extractLESS = new ExtractTextPlugin("[name].css");
const semanticCssPath = path.resolve(__dirname, "node_modules/semantic-ui-css/semantic.min.css");
const datePickerCssPath = path.resolve(__dirname, "node_modules/react-datepicker/dist/react-datepicker.css");
const elasticBuilderPath = path.resolve(__dirname, "node_modules/elastic-builder");
const ifdefOpts = {
build: process.env.BUILD_ENV,
"ifdef-verbose": true,
};
module.exports = {
entry: {
index: APP_DIR + "/client.jsx",
},
output: {
path: BUILD_DIR_CLIENT,
filename: "main_index.js",
},
module: {
rules: [
{
test: /\.less$/,
use: extractLESS.extract(["css-loader?importLoader=2&modules&localIdentName=[name]---[local]---[hash:base64:5]", "postcss-loader", "less-loader"]),
},
{
test: /\.css$/,
include: [semanticCssPath, datePickerCssPath],
use: extractCSS.extract(["css-loader"]),
},
{
test: /\.css$/,
exclude: [semanticCssPath, datePickerCssPath],
use: extractCSS.extract(["css-loader?importLoader=1&modules&localIdentName=[name]---[local]---[hash:base64:5]", "postcss-loader"]),
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: "url-loader?limit=100000",
},
{
test: /\.jsx?/,
include: [APP_DIR, SHARED_DIR, elasticBuilderPath],
use: ["babel-loader", "eslint-loader", {loader: "ifdef-loader", options: ifdefOpts}],
},
],
},
plugins: [
extractLESS,
extractCSS,
],
resolve: {
alias: {
"~": path.resolve(__dirname, "src"),
"#main": path.resolve(__dirname, "src/client/main"),
"#shared": path.resolve(__dirname, "src/shared"),
},
extensions: [".js", ".jsx", ".css", ".less"],
},
};
Writing an answer instead of a comment so I can post some code.
I could not reproduce the issue. The following code works the same on IE11 and Chrome for me.
var myWeakMap = new WeakMap();
function myClass(myObject) {
myWeakMap.set(this, myObject);
}
myClass.prototype.getProperty = function() {
return myWeakMap.get(this).property;
};
var instance = new myClass({property: 5});
console.log(instance.getProperty());
I suspect that the constructor of myClass somehow got undefined in your case. Can you please check it? To do so, insert a console.log in your constructor, and check the logs for output:
class myClass {
constructor(myObject) {
console.log("myClass.constructor", myObject);
myWeakMap.set(this, myObject);
}
// ...
}

Webpack throws TypeError: Super expression must either be null or a function, not undefined when importing LESS file

I have the following in a file initialize.js:
import App from './components/App';
import './styles/application.less';
document.addEventListener('DOMContentLoaded', () => {
const app = new App();
app.start();
});
In webpack.config.js I have:
'use strict';
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const ProvidePlugin = webpack.ProvidePlugin;
const ModuleConcatenationPlugin = webpack.optimize.ModuleConcatenationPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const extractLess = new ExtractTextPlugin({
filename: 'app.css',
});
const webpackCommon = {
entry: {
app: ['./app/initialize']
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader?presets[]=es2015'
}]
}, {
test: /\.hbs$/,
use: {
loader: 'handlebars-loader'
}
}, {
test: /\.less$/,
exclude: /node_modules/,
use: extractLess.extract({
use: [{
loader: 'css-loader'
}, {
loader: 'less-loader'
}],
// use style-loader in development
fallback: 'style-loader'
}),
}]
},
output: {
filename: 'app.js',
path: path.join(__dirname, './public'),
publicPath: '/'
},
plugins: [
extractLess,
new CopyWebpackPlugin([{
from: './app/assets/index.html',
to: './index.html'
}]),
new ProvidePlugin({
$: 'jquery',
_: 'underscore'
}),
new ModuleConcatenationPlugin(),
],
};
module.exports = merge(webpackCommon, {
devtool: '#inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
compress: true,
port: 9000
}
});
I tried removing the the plugins and the contents of application.less, but I keep getting this error:
ERROR in ./node_modules/css-loader!./node_modules/less-loader/dist/cjs.js!./app/styles/application.less
Module build failed: TypeError: Super expression must either be null or a function, not undefined
at ...
# ./app/styles/application.less 4:14-127
# ./app/initialize.js
If I replace that LESS file with a CSS one and update the config it works fine, so I guess the problem has to do with less-loader.
I'm using Webpack 3.4.1, Style Loader 0.18.2, LESS Loader 4.0.5, Extract Text Webpack Plugin 3.0.0 and CSS Loader css-loader.
My bad, I didn't notice I was using an old less version. That was the culprit. Just updated it to 2.7.2 and the problem is gone.

Categories