How to limit scope of webpack - javascript

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"
}

Related

Doing a dynamic import in a loop, walking through the array, but I only get the first value

I am trying to do a dynamic import so that my classes are pulled by information from json. In json, I only have classes specified that I need to get inside the script. I make paths from strings to json then put them in an array.I make an import and put the values ​​into an array. But as a result, I only get the value of the first import, the rest is undefined. Tell me how to correctly perform dynamic imports inside a loop, or is there a fundamentally different approach altogether?
My index.js:
var popupsConfig = myConfig.popups
var popups = []
async function getPopups(popupsConfig) {
for (let i = 0; i < popupsConfig.length; i++) {
let obj = await
import (`../src/assets/popups/${myConfig.popups[i].popupType}`)
popups.push(obj.default)
}
}
getPopups(popupsConfig)
My webpack.config:
const webpack = require("webpack")
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
context: path.resolve(__dirname, '../src'),
mode: 'development',
devtool: "eval-source-map",
entry: {
entry: ['babel-polyfill', '../dev/index.js'],
},
devServer: {
port: 8080
},
experiments: {
topLevelAwait: true
},
resolve: {
alias: {
'#dev': path.resolve(__dirname, '../src/')
}
},
plugins: [
new HtmlWebpackPlugin({
template: '../dev/index.html'
}),
new CleanWebpackPlugin(),
new webpack.DefinePlugin({
CANVAS_RENDERER: JSON.stringify(true),
WEBGL_RENDERER: JSON.stringify(true)
})
],
module: {
rules: [{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpeg|svg|gif)$/,
use: ['file-loader']
}, {
test: [/\.vert$/, /\.frag$/],
use: "raw-loader"
},
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
}
My .babelrc:
{
"plugins": ["dynamic-import-webpack", "#babel/plugin-syntax-dynamic-import"]
}
enter image description here

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 - 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;

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.

Uncaught ReferenceError: require is not defined react + webpack

I have been working on a project for about 2 months and used webpack-dev-middleware.
According to the WDM documentation, its just a wrapper for webpack and run the project in the memory to enable hot reloading.
But now when im trying to build and deploy with webpack and same webpack.config.js i get Uncaught ReferenceError: require is not defined error.
I have searched alot and couldn't find a right answer for my case.
I'd really appreciate any help :).
my webpack.config.js
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var autoprefixer = require('autoprefixer');
const webpack = require('webpack');
var fs = require('fs')
module.exports = {
entry: './src/client.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
target: 'web',
// keep node_module paths out of the bundle
externals: fs.readdirSync(path.resolve(__dirname, 'node_modules')).concat([
'react-dom/server', 'react/addons',
]).reduce(function (ext, mod) {
ext[mod] = 'commonjs ' + mod
return ext
}, {}),
node: {
__filename: true,
__dirname: true
},
plugins: [
new ExtractTextPlugin('styles.css'),
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
}, {
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=100000&name=/[hash].[ext]',
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader']),
},
{ test: /\.json$/, loader: "json-loader"}
],
},
devtool: 'cheap-module-source-map'
}
I'm using webpack version : 1.13.3 as local.
In my case reason was:
...
module: {
noParse: /\.min\.js$/,
...
I've commented it out

Categories