I have recently moved from grunt/bower to webpack but can't get sourcemaps to work. I get code references like debugger://VM8967 instead of real file names like I'm used to. I've tried many combinations of
mode: 'development', devtool: 'cheap-module-source-map',
as suggested in many places, like here and here but without any luck. This seems like very standard behavior that everyone would need so I'm sure I do some stupid mistake. Hope someone can help. I use:
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "^3.7.2"
And my webpack.config looks like this:
const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './app/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, { loader: 'css-loader' }],
},
{
test: /\.(eot|woff|ttf|woff2|svg|png|jpg)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'assets',
},
},
],
},
],
},
plugins: [
new CopyWebpackPlugin([{ from: 'app/images', to: 'images' }]),
new CopyWebpackPlugin([{ from: 'app/languages', to: 'languages' }]),
new CopyWebpackPlugin([{ from: 'app/views', to: 'views' }]),
new CopyWebpackPlugin([{ from: 'app/robots.txt' }]),
new CopyWebpackPlugin([{ from: 'app/404.html' }]),
new CopyWebpackPlugin([{ from: 'app/.htaccess' }]),
new CopyWebpackPlugin([{ from: 'app/favicon.ico' }]),
new CopyWebpackPlugin([{ from: 'app/apple-touch-icon.png' }]),
new HtmlWebpackPlugin({
template: 'app/index.html',
}),
new MiniCssExtractPlugin({
filename: 'style.css',
}),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
},
};
For js source map you can do like this
module.exports = {
// ...
devtool: false,
plugins: [
new webpack.SourceMapDevToolPlugin({
filename: '[name].js.map',
exclude: ['vendor.js']
})
]
};
Link here
Related
I've never used Webpack before and I'm working on a project that's just vanilla JS and HTML. I'm having an issue accessing the values I set in .env. Here's my config.
const path = require("path");
const dotenv = require('dotenv');
var webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = () => {
env = dotenv.config().parsed;
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
entry: {
main: './src/index.js'
},
output: {
path: path.join(__dirname, '../build'),
filename: '[name].bundle.js'
},
mode: 'development',
devServer: {
contentBase: "./src/",
publicPath: "./src/",
compress: true,
port: 9000,
overlay: true,
disableHostCheck: true
},
devtool: 'inline-source-map',
resolve: {
alias: {
process: "process/browser"
}},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpe?g|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/'
}
}
]
},
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
//attributes: ['img:src', ':data-src'],
minimize: true
}
}
}
]
},
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new Dotenv(),
new webpack.DefinePlugin(envKeys),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
}),
]
}
};
As you can see, I'm using dotEnv, definePlugin, and even the dotEnv-webpack plugin. Unfortunately, none of these solutions seem to allow me to access process.env.originURL.
originURL=https://localhost:3000
I'm not importing or requiring anything in my javascript file, index.js. I'm assuming this should work, but the console tells me that process is undefined.
console.log(process.env.originURL);
How can I access process.env.originURL in my index.js?
It should work. Maybe you could try this version:
new Dotenv({ systemvars: true })
If it still doesn't work, please show your package.json, as well as you .env file (randomize the values of course). Is .env at the root of you app?
I am using react and Webpack 5. After running a lighthouse report, I found a few css files that need to be preloaded. How do I do this in Webpack?
webpack config:
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require( 'path' );
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
context: __dirname,
entry: './src/index.js',
output: {
path: path.resolve( __dirname, 'build' ),
filename: '[name].js',
publicPath: '/',
chunkFilename: '[id].[chunkhash].js'
},
optimization: {
chunkIds: "named",
splitChunks: {
chunks: 'all',
},
},
devServer: {
historyApiFallback: true
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
},
{
test: /\.(png|svg|jpg|jpeg|gif|ico)$/,
exclude: /node_modules/,
use: ['file-loader?name=[name].[ext]']
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve( __dirname, 'public/index.html' ),
filename: 'index.html',
favicon: 'public/favicon.ico',
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[name]-[id].css',
}),
new CopyPlugin({
patterns: [
{ from: './src/serviceWorker.js', to: './serviceWorker.js' },
{ from: './public/offline.html', to: './offline.html' },
{ from: './public/manifest.json', to: './manifest.json' },
],
}),
]
};
I tried Magic Comments (as follows) but it did not preload the css.
import (
/* webpackPrefetch: true */
/* webpackPreload: true */
'./Article.css'
);
And I tried PreloadWebpackPlugin, but I could only get it to preload all of the css files in the react project, or none at all.
Ideally, the solution would only include what is needed for the given page...
Any ideas moving forward would be appreciated. Thanks!
Well, as the title says, webpack is not producing what I expect.
Here's my config:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const extractPlugin = new ExtractTextPlugin({
filename: 'main.css',
});
process.env.NODE_ENV = 'production';
module.exports = {
entry: {
main: './src/main.js',
algo: './src/algo.js',
},
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
}
}
],
},
{
test: /\.scss$/,
use: extractPlugin.extract({
use: [
'css-loader',
'sass-loader',
]
})
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.php$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: '/'
}
}
]
},
{
test: /\.(jpg|png|gif|jpeg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: 'images/',
}
}
]
}
],
},
resolve: {
alias: {
vue: 'vue/dist/vue.min'
}
},
plugins: [
extractPlugin,
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
chunks: ['main'],
}),
new HtmlWebpackPlugin({
template: 'src/algo.html',
filename: 'algo.html',
chunks: ['algo']
}),
new CleanWebpackPlugin([
'dist',
]),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Vue: 'vue',
}),
new CopyWebpackPlugin([
{
from: 'src/*.php',
to: '[name].[ext]',
test: /\.php$/
}
]),
],
mode: 'production',
};
Both main.js and algo.js are simply a set of #import 'something's (Please let me know if this a good practice in the comment).
I want to insert the resulting bundles, main.js and algo.js to go into
index.html and algo.html, respectively.
However, so far it's been only producing main.js for index.html so far.
Previously, the output was as follows:
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
However, that didn't work either.
Can someone help me achieve the desired outcome?
You've specified entry twice in your configuration:
entry: {
main: './src/main.js',
algo: './src/algo.js',
},
entry: './src/main.js',
The second entry here is overwriting the first, which means you've only configured ./src/main.js.
I want to exclude this from my webpack file, by using this line of code given to me below.
noParse: /node_modules\/localforage\/dist\/localforage.js/,
But no matter what I try I it keeps on saying errors like
ReferenceError: Unknown plugin "add-module-exports" specified in C:/..../node_modules\localforage\.babelrc
Here is my webpack config file:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
devServer: {
historyApiFallback: true,
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
You can use localForage 1.3+ version with webpack. You should add noParse in your config.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
devServer: {
historyApiFallback: true,
},
module: {
noParse: /node_modules\/localforage\/dist\/localforage.js/,
rules: [{
test: /\.(js)$/,
exclude: /localforage/,
use: 'babel-loader'
}, {
test: /\.css$ / ,
use: ['style-loader', 'css-loader']
}]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
The follow production webpack.config file mostly works (builds, runs ok), but one nagging problem. I set up vendor and app js outputs precisely to separate vendor code (since those don't change very often). However, with the .config setup, even if there is no change, I always get a different chunk hash for vendor and app.js. I must be setting this wrong somehow but I have no idea what it could be. Please help!
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var AssetsPlugin = require('assets-webpack-plugin');
var ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
var app_dir = path.join(__dirname, 'app');
var config = {
entry: {
vendors: ['react', 'react-dom', 'moment'],
app: path.resolve(__dirname, 'app/Main.js')
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
},
module: {
loaders: [{
test: /\.jsx?$/, // A regexp to test the require path. accepts either js or jsx
exclude: [node_modules_dir],
loader: 'babel', // The module to load. "babel" is short for "babel-loader"
},
// LESS
{
test: /\.less$/,
loader: 'style!css!less'
},
{
test: /\.css$/, // Only .css files
loader: 'style!css' // Run both loaders
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
},
{ test: /\.gif$/, loader: "url-loader?mimetype=image/png" },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=[name].[ext]" }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendors",
minChunks: Infinity
}),
new AssetsPlugin({
filename: 'webpack-assets.js',
path: path.resolve(__dirname, 'dist'),
processOutput: function (assets) {
return 'window.staticMap = ' + JSON.stringify(assets);
}
}),
new ChunkManifestPlugin({
filename: "chunk-manifest.json",
manifestVariable: "webpackManifest"
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
},
'__appSettings': {
'apiGatewayDomain': '"http://localhost:8088"',
'enableDevTools': false,
'enableReduxLogger': false
},
__version: JSON.stringify(require(__dirname +"/package.json").version)
}),
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!isomorphic-fetch',
'configureApplicationStore': 'exports?configureStore!' + app_dir + '/global/redux/ConfigureStore.prod.js'
})
]
};
module.exports = config;
If there are other glaring issues with this setup, please let me know as well. Thanks!
use the "key sort" to fixed vendor.
you entry just like this:
entry: {
a_vendors: ['react', 'react-dom', 'moment'],
z_app: path.resolve(__dirname, 'app/Main.js')
},
the vendor will fixed.
more detail:
https://github.com/webpack/webpack/issues/1315#issuecomment-247269598
https://github.com/webpack/webpack/pull/2998