Given the following existing webpack.config.babel.js that's working fine for this application, I would like to add another entry (widget), but if I do so, it requires all external items to be loaded in my HTML page even when I don't need it with my new feature (google, leaflet...) on this part of the application.
widget.js:10488 Uncaught ReferenceError: google is not defined
The plugin & resolve & output existing sections are applying to the new entry js I want to add, so it's good. Only the external is bothering me.
What's the best way to resolve this ? I have very little knowledge of webpack. Thanks.
import path from 'path';
import webpack from 'webpack';
import eslintFormatter from 'eslint-friendly-formatter';
export default (env) => {
const isProd = env ? !!env.release : false;
const isVerbose = env ? !!env.verbose : true;
process.env.NODE_ENV = isProd ? 'production' : 'development';
return {
entry: {
showcase: path.resolve(process.cwd(), 'src/AppBundle/Resources/private/js/showcase/index.js'),
// widget: path.resolve(process.cwd(), 'src/AppBundle/Resources/private/js/widget/index.js'),
},
output: {
path: path.resolve(process.cwd(), 'web/dist/components'),
filename: '[name].js',
publicPath: '/',
},
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
Translator: 'node_modules/bazinga-translator/js',
},
},
externals: {
vue: 'Vue',
vuex: 'Vuex',
google: 'google',
leaflet: 'L',
translator: 'Translator',
markerclustererplus: 'MarkerClusterer',
lodash: '_',
routing: 'Routing',
},
module: {
rules: [
{
test: /\.(js|vue)$/,
enforce: 'pre',
include: path.resolve(process.cwd(), 'src/AppBundle/Resources/private/js'),
use: {
loader: 'eslint-loader',
options: {
formatter: eslintFormatter,
},
},
},
{
test: /\.js$/,
include: path.resolve(process.cwd(), 'src/AppBundle/Resources/private/js'),
use: 'babel-loader',
},
{
test: /\.vue$/,
use: 'vue-loader',
},
],
},
plugins: [
// Define environment variables
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),
// No compile changes on errors
...isProd ? [] : [new webpack.NoEmitOnErrorsPlugin()],
// JavaScript code minimizing
...isProd ? [
// Minimize all JavaScript output of chunks
// https://github.com/mishoo/UglifyJS2#compressor-options
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: isVerbose,
},
}),
] : [],
],
watchOptions: {
aggregateTimeout: 300,
poll: 1000,
},
};
};
Externals is only configuration suppose modules will be exists but webpack does not call it itself. It is possible alredy existed entry loaded togather with all externals and worked fine with no errors. But new entry loaded without loading externals and new entry make (or some else) call not loaded externals. Check you possible have dependencies requiers some externals or your newely added entry make call some of externals (which actually is not loaded in second case).
Related
I've been struggling with something (react, but doesn't matter).
Imagine the following setup:
// modules/A/index.ts
export { actions } from '/actions'
export { default as RootComponent } from './component' // imagine this to be big, I tried adding 250kb of data to it.
export { default as reducer } from './reducer'
export { default as saga } from './saga'
Now.. In the app, there is the following:
// index.js
import {actions} from './modules/A';
const LazyComponent = React.lazy(() => import('./modules/A').then(res => {
// doing something with the reducer/saga
return {default: res.RootComponent}
}));
// LazyComponent as a route, using an action from actions to trigger something (if present)
All this works fine, except, the moment when I statically import the actions from the module, no chunk will be generated anymore and everything ends up in the main js. If I would import the actions from the actions file itself from the module, it will generate a chunk for the dynamic import, like desired.
If there anything that can be done to get my desired effect:
statically import something from the module, but load the rest only on demand (because of the size)?
The idea is, that the module might be extracted as a dependency later on (es module), and then the pkg.module will be some index, so how to support code splitting like that?
Simplified Webpack config (copy from a different project, didn't really go through it yet) (v4.43):
const config = {
target: 'web',
entry: {
app: './src/index.tsx',
},
output: {
filename: '[name].[chunkhash].bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: '/',
},
resolve: {
extensions: ['.tsx', '.ts'],
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: 'thread-loader',
options: {
poolTimeout: isProduction ? 500 : Infinity,
},
},
{
loader: 'ts-loader',
options: {happyPackMode: true},
},
],
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(ttf|eot|svg|jpg|gif|png|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader',
},
],
},
plugins: [
...(isProduction ? new CleanWebpackPlugin() : []),
new webpack.DefinePlugin({
PRODUCTION: isProduction,
}),
new htmlWebpackPlugin({template: './src/index.html'}),
new CopyWebpackPlugin({
patterns: [
{
context: './public',
from: '**/*',
},
]
}),
new CircularDependencyPlugin({
exclude: /node_modules/,
failOnError: true,
}),
],
devServer: { /* blabla*/ },
optimization: {
noEmitOnErrors: true,
},
stats: {
warningsFilter: /export .* was not found in/,
},
}
I've been googling for a couple hours now and can't seem to resolve my issue.
I have a webpack/React/Typescript/Mobx setup and am attempting to use firebase.
Here is my webpack config: (boilerplate from this repo)
var webpack = require('webpack');
var path = require('path');
// variables
var isProduction = process.argv.indexOf('-p') >= 0;
var sourcePath = path.join(__dirname, './src');
var outPath = path.join(__dirname, './dist');
// plugins
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WebpackCleanupPlugin = require('webpack-cleanup-plugin');
module.exports = {
context: sourcePath,
entry: {
main: './main.tsx'
},
output: {
path: outPath,
filename: 'bundle.js',
chunkFilename: '[chunkhash].js',
publicPath: '/'
},
target: 'web',
resolve: {
extensions: ['.js', '.ts', '.tsx'],
// Fix webpack's default behavior to not load packages with jsnext:main module
// (jsnext:main directs not usually distributable es6 format, but es6 sources)
mainFields: ['module', 'browser', 'main'],
alias: {
app: path.resolve(__dirname, 'src/app/'),
assets: path.resolve(__dirname, 'src/assets/')
}
},
module: {
rules: [
// .ts, .tsx
{
test: /\.tsx?$/,
use: [
isProduction
? 'ts-loader'
: {
loader: 'babel-loader',
options: {
babelrc: false,
plugins: ['react-hot-loader/babel']
}
},
'ts-loader'
],
// : ['babel-loader?plugins=react-hot-loader/babel&presets=', 'ts-loader'],
exclude: /node_modules/
},
// css
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
query: {
modules: true,
sourceMap: !isProduction,
importLoaders: 1,
localIdentName: '[local]__[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('postcss-import')({ addDependencyTo: webpack }),
require('postcss-url')(),
require('postcss-cssnext')(),
require('postcss-reporter')(),
require('postcss-browser-reporter')({
disabled: isProduction
})
]
}
}
]
})
},
{
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader']
},
// static assets
{ test: /\.html$/, use: 'html-loader' },
{ test: /\.(png|jpg)$/, use: 'url-loader?limit=10000' },
{ test: /\.webm$/, use: 'file-loader' }
]
},
optimization: {
splitChunks: {
name: true,
cacheGroups: {
commons: {
chunks: 'initial',
minChunks: 2
},
vendors: {
test: /[\\/]node_modules[\\/]/,
chunks: 'all',
priority: -10
}
}
},
runtimeChunk: true
},
plugins: [
new WebpackCleanupPlugin(),
new ExtractTextPlugin({
filename: 'styles.css',
disable: !isProduction
}),
new HtmlWebpackPlugin({
template: 'assets/index.html'
})
],
devServer: {
contentBase: sourcePath,
hot: true,
inline: true,
historyApiFallback: {
disableDotRule: true
},
stats: 'minimal'
},
devtool: 'cheap-module-eval-source-map',
node: {
// workaround for webpack-dev-server issue
// https://github.com/webpack/webpack-dev-server/issues/60#issuecomment-103411179
fs: 'empty',
net: 'empty'
}
};
Just by including firebase in my app i relentlessly end up with this error:
Uncaught TypeError: Cannot read property 'navigator' of undefined auth.esm.js?69b5:10
I have tested by including a simple component like so:
import * as React from 'react';
import * as Styles from './styles.css';
import 'app/utils/FirebaseUtil';
interface TestProps {}
export const Test: React.StatelessComponent<TestProps > = () => (
<div className={Styles.root}>
{'Hello World'}
</div>
);
FirebaseUtil:
import * as firebase from 'firebase';
const config = {
apiKey: '**my key here**',
authDomain: '** my domain here **'
};
firebase.initializeApp(config);
export const fbAuth = firebase.auth;
No matter what I seem to do I get the navigator error. Even if i dont export the auth object. As far as I can tell its related to babel-loader adding strict-mode according to this SO question, i think? All other related searches seem to have to do with firebase-ui, which i am not using in any way.
But I have no idea how he manages to turn off strict mode, not to mention the OP is not using typescript and I am using ts-loader in this case. I can't for the life of me figure out how to get it working. Aside from all of this if I do try use the firebase object for auth() for example I get a bunch of warnings from webpack about auth not existing on the firebase object. Totally stumped.
So in case anyone else runs into this problem. It appears it was a package version issue. Im assuming that the package versions specifically included in the boilerplate i used didn't play well with firebase.
I updated typescript, react-hot-loader, and most likely the issue webpack from version 3.0.4 to 4.12.1 and things seem to be working ok now. Also with the updates I now import firebase like so:
import firebase from '#firebase/app';
import '#firebase/auth';
Hope this helps someone.
In my case I fixed this importing functions
import firebase from 'firebase/app'
import 'firebase/functions'
import 'firebase/analytics'
After I've updated webpack from 3.11.0 to 4.6.0, breakpoints in Angular Typescript started moving automatically at the end of the file during debug.
If I stop debug, they returns where I've placed them.
EXAMPLE (which will explain the situation better than my intro above)
If I have - for example - a .ts file of 100 lines and I set a
breakpoint on typescript on Visual Studio at line 50, when I run my
app debug, the breakpoints moves automatically at the end of the file
(so at line 100). When I stop debug, it returns on line 50.
The issue started when I've updated Webpack to last version and seems like to be related to sourcemap.
I share with you my webpack.config.js content below. After the code snippet, I will also tell you what I've changed from 3.11.0 to 4.6.0.
Can anyone help me to solving this?
P.S.: I've kept the default line that enable in-line sourcemaps if you delete or comment it in the config file (see comment Remove this line if you prefer inline source maps in my code below) because using in-line sourcemaps on typescript literally kills my computer.
MY CODE BELOW
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('#ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const isClient = typeof window !== 'undefined';
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
context: __dirname,
resolve: { extensions: ['.js', '.ts'] },
output: {
filename: '[name].js',
publicPath: 'dist/', // Webpack dev middleware, if enabled, handles requests for this URL prefix
globalObject: 'self'
},
module: {
rules: [
{ test: /\.ts$/, include: /ClientApp/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: ['to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
//font management
{
test: /\.(svg|eot|ttf|woff|woff2)$/,
use: [{
loader: 'file-loader',
options: {
name: 'images/[name].[hash].[ext]'
}
}]
}
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
optimization: {
minimizer: [
// specify a custom UglifyJsPlugin here to get source maps in production
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true
},
sourceMap: true
})
]
},
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
WHAT CHANGED BETWEEN VERSIONS
webpack.config.js
1. - moved uglify from plugins to optimization, but copy-pasting this configuration from the internet. (Maybe the issue is related to this?)
optimization: {
minimizer: [
// specify a custom UglifyJsPlugin here to get source maps in production
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true
},
sourceMap: true
})
]
},
2. - removed AOT webpack plugin from production environment configuration
Solved by disabling browser link in Visual Studio 2017.
Also set "sourcemap:true" on tsconfig.
Version
2.5.13
Link to the source code
https://jsfiddle.net/esrgxLfu/
Description
I have a PHP application which uses Vue JS mainly for the settings page. All of settings is created with Vue and we use Webpack. Everything works fine and when we are in the live version there is no console error about Vue being in development mode. We use Vue also for only one component on the dashboard page. It is a Vue TODO list like the one in the Vue documentation. On the dashboard page, we get the console message that Vue is in development mode. We use same Webpack for dashboard and settings page hence the same settings.
I have looked for hours to try to find an answer but I have not been successful which is why I am creating this issue.
In the php file we have this to place the vue component in:
<div id="vue-tasks"></div>
and then we included the javascript file plus the variables.
You can see everything that's being used in the fiddle but I really don't think I can make this reproducible, I'm sorry if you cannot help me with this but it is using a bunch of stuff from PHP Symfony and twig so I was not sure what I could do.
What is expected?
Vue to be in production mode.
What is actually happening?
Vue is in dev environment.
Webpack configuration
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
dashboard: [
'./assets/js/pages/dashboard.js' // Dashboard is the part where we have this issue and the JS is in the fiddle I provided above.
],
settings: [
'./assets/js/pages/settings/main.js'
]
},
output: {
filename: process.env.NODE_ENV === 'production' ? 'js/[name].[chunkhash].js' : 'js/[name].js',
path: path.resolve(__dirname, 'web/dist'),
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}
]
},
{
test: /\.js$/,
include: path.resolve(__dirname, "assets"),
use: ['babel-loader']
},
{
test: /\.(woff2?|ttf|eot|svg)$/,
loader: 'url-loader?limit=10000&name=fonts/[name].[ext]'
},
{
test: /\.scss$/,
include: path.resolve(__dirname, "assets"),
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader','resolve-url-loader','sass-loader?sourceMap']
})
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader','resolve-url-loader']
})
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}
}
},
]
},
resolve: {
alias: {
jquery: "jquery/src/jquery",
'vue$': 'vue/dist/vue.esm.js'
}
},
plugins: [
new ExtractTextPlugin({
filename: process.env.NODE_ENV === 'production' ? 'css/[name].[chunkhash].css' : 'css/[name].css'
}),
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
}),
new WebpackMd5Hash(),
new ManifestPlugin({
basePath: '/dist/'
})
],
performance: {
hints: false
},
devtool: 'source-map'
};
if (process.env.NODE_ENV === 'production') {
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
comments: false,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}),
new CleanWebpackPlugin('dist' , {
root: path.resolve(__dirname, "web"),
verbose: true,
dry: false
})
])
}
Also this is the message I get in console.
You are running Vue in development mode. Make sure to turn on
production mode when deploying for production. See more tips at
https://vuejs.org/guide/deployment.html
It looks like you are picking Vue up using a browser script tag rather than as part of a bundle from your build system.
Altering this to link to a production version of Vue will resolve the issue. In your jsfiddle, for example, replace the script link with https://unpkg.com/vue/dist/vue.min.js.
https://babeljs.io/docs/usage/polyfill/#usage-in-browser
I did not understand the lines on the documentation page under:
Usage in Browser heading
can someone help me with what else is required:
Below are my code snippets:
I'm using storybook as a boilerplate:
webpack.config.js file:
entry: [
'babel-polyfill',
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs
]
index.js file:
import 'babel-polyfill';
import React from 'react';
Is there some other files also where I need to add babel-polyfill related code.
require('babel-polyfill');
var path = require('path');
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
var getClientEnvironment = require('./env');
var paths = require('./paths');
var publicPath = '/';
var publicUrl = '';
var env = getClientEnvironment(publicUrl);
module.exports = {
devtool: 'cheap-module-source-map',
entry: ['babel-polyfill',
require.resolve('react-dev-utils/webpackHotDevClient'),
require.resolve('./polyfills'),
paths.appIndexJs
],
output: {
path: paths.appBuild,
pathinfo: true,
filename: 'static/js/bundle.js',
publicPath: publicPath
},
resolve: {
fallback: paths.nodePaths,
extensions: ['.js', '.json', '.jsx', ''],
alias: {
'react-native': 'react-native-web'
}
},
module: {
// First, run the linter.
// It's important to do this before Babel processes the JS.
preLoaders: [{
test: /\.(js|jsx)$/,
loader: 'eslint',
include: paths.appSrc,
}],
loaders: [{
exclude: [/\.html$/, /\.(js|jsx)$/, /\.css$/, /\.json$/],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel',
query: {
cacheDirectory: true
}
}, {
test: /\.css$/,
loader: 'style!css?importLoaders=1!postcss'
}, {
test: /\.json$/,
loader: 'json'
}
]
},
// We use PostCSS for autoprefixing only.
postcss: function() {
return [
autoprefixer({
browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
},
plugins: [
new InterpolateHtmlPlugin({
PUBLIC_URL: publicUrl
}),
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
new webpack.DefinePlugin(env),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new WatchMissingNodeModulesPlugin(paths.appNodeModules)
],
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
There are two ways to get this code into your browser.
1 - Include the babel-polyfill module in the webpack bundle
2 - Load it as an external script in your html
Webpack - adding bundle dependencies with entry arrays
Put an array as the entry point to make the babel-polyfill module available to your bundle as an export.
With webpack.config.js, add babel-polyfill to your entry array.
The webpack docs explain how an entry array is handled:
What happens when you pass an array to entry? Passing an array of file
paths to the entry property creates what is known as a "multi-main
entry". This is useful when you would like to inject multiple
dependent files together and graph their dependencies into one
"chunk".
Webpack.config.js
require("babel-polyfill");
var config = {
devtool: 'cheap-module-eval-source-map',
entry: {
main: [
// configuration for babel6
['babel-polyfill', './src/js/main.js']
]
},
}
Alternative to Webpack - load babel-polyfill as an external script in the browser html
The alternative to using webpack would mean including the module as an external script in your html. It will then be available to code in the browser but the webpack bundle won't be directly aware of it.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.22.0/polyfill.js"></script>