Idk why but all my code runs twice when I run webpack-dev-server(webpack serve)...
my folders path:
dist
src
js
app.js
loadBro.js
scss
main.scss
index.html
List item
here is my webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
app:'./src/js/app.js',
loadBro: './src/js/loadBro.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devtool: 'inline-source-map',
devServer:{
open:true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
chunks: ['app', 'loadBro'],
}),
module: {
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader','sass-loader']
},
],
},
};
you already applied plugins: [new HtmlWebpackPlugin({template: ...}) then no need add <script src="bundle whatever u give here"></script>
Related
Hi I have the following problem with my Webpack Config:
I want to have 3 different .js files from my src folder. Each file is supposed to be connected to only the corresponding html file with the same name:
Example: I want app.html only to inject app.js and not index.js and register.js as well.
As for now, Webpack generates 3 html files and 3 .js files, however every .html file gets referenced all 3 .js files, which breaks my code, since I don't have the corresponding id's for eventlisteners in index that the code written app.js.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: ['./src/js/index.js'],
register: ['./src/js/register.js'],
app: ['./src/js/app.js'],
},
output: {
filename: '[name].js',
path: __dirname + '/dist',
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
chunks: 'index',
template:'./src/index.html',
filename: './src/index.html'
}),
new HtmlWebpackPlugin({
inject: true,
chunks: 'register',
template:'./src/register.html',
filename: './src/register.html'
}),
new HtmlWebpackPlugin({
inject: true,
chunks: 'app',
template:'./src/app.html',
filename: './src/app.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
};
Here you have an example adding one chunks to the html
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const config = [{
site: 'index'
}, {
site: 'register'
}, {
site: 'app'
}];
const entryHtmlPlugins = config.map(({
site
}) => {
return new HtmlWebPackPlugin({
filename: `${site}.html`,
chunks: [site],
});
});
module.exports = {
mode: 'production',
entry: {
index: './src/js/index.js',
register: './src/js/register.js',
app: './src/js/app.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, './dist'),
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
}, ],
},
plugins: [...entryHtmlPlugins],
};
My webpack config gives the following error Multiple assets emit different content to the same filename index.html
when I delete the htmlWebpackPlugin it works, but I won't get any html to show. I'm using Vue.js and my config looks like this:
const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = (env, argv) => ({
mode: argv && argv.mode || 'development',
devtool: (argv && argv.mode || 'development') === 'production' ? 'source-map' : 'eval',
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
node: false,
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
exclude: /\.module\.css$/
}
]
},
resolve: {
extensions: [
'.js',
'.vue',
'.json'
],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, 'src')
}
},
plugins: [
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['dist']
}),
new VueLoaderPlugin(),
new HtmlWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [{
from: path.resolve(__dirname, 'static'),
to: path.resolve(__dirname, 'dist'),
toType: 'dir'
}]
})
],
devServer: {
compress: true,
host: 'localhost',
https: true,
open: true,
overlay: true,
port: 9000
}
});
My file structure looks like this
I've looked at Conflict: Multiple assets emit to the same filename but no solution worked for me, are there any other options?
Could it be that Vue loader also emits index.html?
Try:
new HtmlWebpackPlugin({
template: './index.html',
filename: 'anotherFileName.html',
}),
I'm not really familiar with webpack and I have this issue where I can't access my assets on prod - it returns 404
I have this structure:
- repo
- public
- index.html
- images
- animals
- dog.png
- audio
- growl.mp3
- src
- index.js
... other files
Now on my index.js (or other files) I access the images by doing:
import { Loader, utils, Sprite, AnimatedSprite } from 'pixi.js'
loader
.add('images/animals/dog.png' )
.load(async () => {})
... other codes
And this works fine on local, but when I deploy on production It throws
Failed to load resource: the server responded with a status of 404 () - /images/animals/dog.png:1 Failed to load resource: the server responded with
My webpack looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CircularDependencyPlugin = require('circular-dependency-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
mode: isProd ? 'production' : 'development',
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/',
},
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
devtool: isProd ? 'cheap-module-eval-source-map' : 'source-map',
devServer: {
hot: true,
watchContentBase: true,
contentBase: [
path.resolve(__dirname, 'public'),
path.resolve(__dirname, 'build'),
],
publicPath: '/',
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
},
},
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: false,
cwd: process.cwd(),
}),
new CopyWebpackPlugin([
{ from: 'public/audio', to: 'audio' },
{ from: 'public/images', to: 'images' },
]),
],
}
Ok, so I figured it out.
It turns out that I just need to make all publicPath to '' (empty string)
When I run webpack-dev-server, with a publicPath of /dist, I'm able to see live-edits for my app (changes to html, styling, js). However, when I compile the app into a production build, the stylesheet and javascript load from /dist/main.css and /dist/main.js instead of from main.css and main.js
The problem seems to be with the publicPath setting. If I remove publicPath, the app compiles with main.css and main.js, but I'm not able to see live edits. However, if I keep publicPath: /dist I can see live edits, but now I get /dist/main.css and /dist/main.js
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/js/app.js',
output: {
filename: 'main.bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist'
}, //js output object
module: {
rules: [
{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
}, //sass to css
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
]
} //babel
]
}, //module object
plugins: [
new MiniCssExtractPlugin({
filename: '[name].min.css',
chunkFilename: '[id].min.css'
}),
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: 'http://localhost:8080/dist'
}),
new HtmlWebpackPlugin({
template: './src/index.html',
/* minify: {
collapseWhitespace: true
}*/
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', {discardComments: {removeAll: true}}]
},
canPrint: true
})
] //plugins array
}
I am trying to load a pdf into my angular app running on webpack dev server using HTML <object> tag with data attribute.
Since the pdf path is generated at run time and is absolute like C:\test.pdf.
It is not loaded into the UI but rather console logs the error -
Not allowed to load local resource: file:///C:/test.jpeg
However the production build of the app which doesn't run on hosting server but as static html works fine. Also, relative path works fine as well.
How can i load the pdf ?
webpack.common.js
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
module.exports = {
resolve: {
extensions: ['.js', '.ts'],
modules: [rootDir, path.join(rootDir, "node_modules")]
},
module: {
rules: [
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[ext]'
},
{
test: /\.(scss|css)$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader",
options: {
includePaths: ["node_modules/"]
}
}
]
}
]},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)#angular/,
path.resolve(__dirname, '../src')
)
]
};
webpack.dev.js
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
commonConfig.entry = {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
};
commonConfig.module.rules.unshift({
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader', 'angular-router-loader']
});
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: path.resolve(rootDir, 'dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[name].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});
You could tell the devServer from where to serve files.
devServer: {
historyApiFallback: true,
stats: 'minimal',
contentBase: ['./dist', 'C:\\']
}
Then you can load your file with <... src="/file_name.ext" ... />
But I would not recommend adding C:\ as contentBase. If you have the possiblity, define another output directory for your generated PDF.