Webpack unable to find the correct modules - express

I cannot figure out why the paths are so wrong when finding node modules. Here's my /webpack-dev-server.js
const chalk = require('chalk');
const webpack = require('webpack');
const env = require('../server/environment');
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = require('./webpack.config.development.js');
const server = new WebpackDevServer(webpack(webpackConfig), {
publicPath: '/client',
contentBase: '/client',
inline: true,
hot: true,
compress: true,
stats: false,
quiet: true,
noInfo: true,
lazy: false,
historyApiFallback: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Requested-With'
},
proxy: {
"*": 'http://localhost:3000'
}
});
server.listen(env.WEBPACK_PORT, 'localhost', (err) => {
if (err) {
console.log(chalk.red(err));
}
console.log(chalk.yellow(`Webpack server listening on http://localhost:${env.WEBPACK_PORT}`));
});
which includes the basic webpack development setup. When I start up the webpack-dev-server above, I get the following error in the console:
AppContainer.scss?048e:4Uncaught Error: Cannot find module "!!./../../../node_modules/css-loader/index.js?modules!./../../../node_modules/autoprefixer-loader/index.js!./../../../node_modules/sass-loader/index.js!./AppContainer.scss"
I see the paths to the node_modules are incorrect. What's strange is that if I run an Express server and simply require the webpack-dev-server it works...
Here's my webpack config:
import path from 'path';
import webpack from 'webpack';
import env from '../server/environment';
export default {
target: 'web',
devtool: 'cheap-module-eval-source-map',
entry: [
`webpack-dev-server/client?http://localhost:${env.WEBPACK_PORT}`,
'webpack/hot/dev-server',
'babel-polyfill',
'./client/index'
],
output: {
path: path.join(__dirname, '../client'),
pathInfo: true,
publicPath: `http://localhost:${env.WEBPACK_PORT}/client/`,
filename: 'index.js'
},
resolve: {
root: path.join(__dirname, '..'),
modulesDirectories: [
'node_modules',
'client'
],
extensions: ['', '.json', '.js']
},
plugins: [
new webpack.DefinePlugin({
__DEV__: env.isDev,
__PRODUCTION__: env.isProd,
__TOKEN_KEY__: JSON.stringify(env.TOKEN_KEY),
__ENV__: JSON.stringify(env.ENV)
}),
new webpack.HotModuleReplacementPlugin()
],
module: {
noParse: /\.min\.js/,
loaders: [
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file' },
{ test: /\.(woff|woff2)$/, loader: 'file-loader?prefix=font/&limit=5000' },
{
test: /\.ttf(\?v=\d+.\d+.\d+)?$/,
loader: 'file-loader?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.svg(\?v=\d+.\d+.\d+)?$/,
loader: 'file-loader?limit=10000&mimetype=image/svg+xml'
},
{ test: /\.(jpe?g|png|gif)$/i, loaders: ['file'] },
{ test: /\.ico$/, loader: 'file-loader?name=[name].[ext]' },
{ test: /\.json$/, loader: 'json' },
{ test: /\.scss$/, loader: 'style!css?modules!autoprefixer!sass' },
{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/
}
]
}
};

I needed to correctly extend the base config class.

Related

Debugging in Chrome Sources tab showing webpack folder with multiple version of vue files

Something happened recently as this was working fine. I am unable to debug vue files in the sources tab like I used to do.
Currently it shows different versions of each vue file, and all of them are compressed, and they don't show the file. Also extra folders like lang sync^\ that I did not created.
I tried to add a workspace in Filesystem Tab, it did not help.
I looked in Chrome, and Firefox and both have the same problem.
This is the webpack code.
module.exports = env => {
return {
mode: 'development',
entry: {
main: ['babel-polyfill', './src/js/main.js']
},
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: [
/node_modules/
]
},
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
outputPath: (url, resourcePath, context) => {
if (url.indexOf('logo') !== -1) {
return `./brand/${env}/${url}`;
}
return `./src/assets/cards/${url}`;
}
}
},
{
test: /\.(svg)$/,
loader: 'html-loader', // since svg is an inline image
options: {
name: '[name].[ext]',
outputPath: './src/assets'
}
},
{
test: /\.ico$/,
loader: 'file-loader',
options: {
name: '[name].ico',
outputPath: '/'
}
},
{
test: /\.(woff|woff2|eot|ttf)(\?v=[0-9]\.[0-9]\.[0-9])?$/, // todo include svg
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: './fonts'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js',
'scss': path.resolve(__dirname, './src/scss'),
'$assets': path.resolve(__dirname, './src/assets'),
'$brand': path.resolve(__dirname, './brand')
},
modules: [
'node_modules',
path.resolve(__dirname),
path.resolve(__dirname, 'src/assets')
],
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true,
allowedHosts: Object.values(BRANDS),
port: PORT,
publicPath: '/dist/',
before: function (app) {
console.log('listening on ' + Object.values(BRANDS).join(' and ') + ' on port ' + PORT);
}
},
performance: {
hints: false
},
devtool: '#inline-source-map',
plugins: [
new VueLoaderPlugin(),
new webpack.DefinePlugin(processEnv),
new HtmlWebpackPlugin({ //Generates an HTML file for your application by injecting automatically all your generated bundles.
title: '...',
template: 'template.html',
filename: 'index.html',
hash: true,
meta: {
viewport: 'width=device-width,initial-scale=1,user-scalable=no'
}
}),
],
}
};
Try to add this to vue.config.js
module.exports = {
//...
configureWebpack: config => {
if (process.env.NODE_ENV === 'development') {
config.devtool = 'eval-source-map';
config.output.devtoolModuleFilenameTemplate = info =>
info.resourcePath.match(/\.vue$/) && !info.identifier.match(/type=script/)
? `webpack-generated:///${info.resourcePath}?${info.hash}`
: `webpack-yourCode:///${info.resourcePath}`;
config.output.devtoolFallbackModuleFilenameTemplate = 'webpack:///[resource-path]?[hash]';
}
},
// ...
}
Read more

Webpack 5: how to disable copying static files to build folder?

I am used webpack 2 for project, and some days ago I have upgraded to version 5.6.
2-3 hours and project compiling OK, but I have just one problem.
All static files (images, fonts) I store in /static/ folder.
CSS file:
.link-yellow{
background-image: url("/static/wifi2.png");
}
.link-red{
background-image: url("/static/wifi4.png");
}
.link-grey{
background-image: url("/static/wifi3.png");
}
Webpack 2 after compiling JS bundle file don't touch css url(...) links but webpack 5 copying files to folder /build/ and finally I have this:
4e4b4524859364a45966.png
5b97c8a6a9b9aa05b4be.otf
7ed064d8178174fa9ce1.woff2
14d3902c59ccd98328c8.png
440e51cee01b3e78fed5.png
664550a92a1dbb39a80a.png
build.js
And this records (like 4e4b4524859364a45966.png) in build.js:
...3197:function(t,e,n){"use strict";t.exports=n.p+"4e4b4524859364a45966.png"}...
Build progress:
I tried to use file-loader with this params:
module: {
rules: [
....
{
test: /\.(png|svg|jpg|jpeg|gif|gif|woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options:{
emitFile: false,
name: '[name].[ext]'
}
}
....
]
}
but after that I have the same files in /build/ folder with texts inside like this:
export default __webpack_public_path__ + "wifi2.png";
export default __webpack_public_path__ + "exo2.otf";
export default __webpack_public_path__ + "wifi3.png";
I moved some images files to style="..." attributes in vue files:
<div id="mainFooter" style="background: transparent url('/static/wifi3.png') no-repeat 0 0">
and webpack don't touch this text and not generate copies of static files in /build/ folder and all works fine. It is that I need.
Full source of webpack.config.js:
var path = require('path');
var webpack = require('webpack');
const { VueLoaderPlugin } = require('vue-loader');
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
mode: 'production',
plugins: [
new VueLoaderPlugin()
],
module: {
rules: [
{
test: /\.styl$/,
use: ['style-loader', 'css-loader', 'stylus-loader']
},
{
test: /\.css$/,
use: ['vue-style-loader','css-loader']
},
{
test: /\.scss$/,
use: ['vue-style-loader','css-loader','sass-loader'],
},
{
test: /\.sass$/,
use: ['vue-style-loader','css-loader','sass-loader?indentedSyntax'],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
],
'sass': [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|svg|jpg|jpeg|gif|gif|woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options:{
emitFile: false,
name: '[name].[ext]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
client: {
overlay: true,
},
static: './'
},
performance: {
hints: false
},
devtool: 'eval-source-map',
optimization: {
minimize: true,
portableRecords: true,
removeAvailableModules: true,
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
format: {
comments: false,
},
},
extractComments: false
})
]
}
};
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = 'inline-nosources-cheap-source-map';//source-map
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Maybe someone know how to disable generating static files in /build/ folder and leave files url's in css with no modifying paths?
UPDATE:
I have some progress. Code disabling touching urls in css files, but fonts still copying:
{
test: /\.css$/,
use: ['vue-style-loader']
},
{
test: /\.css$/,
loader: 'css-loader',
options: {
url: false,
},
},
UPDATE2: Done. Adding:
{
test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
type: "asset",
}
finally disabling generate other files. At now generating only /build/build.js file

Vue+Webpack configuration

I try to use Vue2 with Webpack4. Command webpack-dev-server finished with success, but it shows me only folders:
My webpack.config.js is:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
entry: './src/main.js',
output: {
publicPath: './',
path: path.join(__dirname, '/dist'),
filename: 'result.js',
},
devServer: {
compress: true,
port: 8532,
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.s[ac]ss$/i,
use: [
{ loader: 'vue-style-loader' },
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /\.(png|jpg|gif)$/,
exclude: [path.resolve(__dirname, "public/fonts")],
use: ['file-loader'],
},
],
},
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: './public/index.html',
minify: false,
})
],
};
This is my first experience with Vue.
What am I doing wrong?
Before that I tried to use vue-cli, but as I understood I can't use scss and Pug without Webpack.
Am I right?

vuejs CLI erroro with awesome font

I am working vue CLI webpack setup and installed the awesome font package via npm. In the in the main.js i imported the font:
import 'vuetify/dist/vuetify.min.css'
i got the following error:
./node_modules/font-awesome/fonts/fontawesome-webfont.ttf?v=4.7.0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./node_modules/css-loader!./node_modules/font-awesome/css/font-awesome.css 7:684-735
# ./node_modules/font-awesome/css/font-awesome.css
# ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
# ./src/App.vue
# ./src/main.js
# multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js
and heres the standard webpack config file:
any ideas how to use the right loader?
regards
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: 'dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
You don't need to plug vue-style-loader for css loading. This is an internal loader used by vue-loader.
rules: [
{
test: /\.css$/,
use: [
- 'vue-style-loader',
'css-loader'
],
}, {
You also need a loader for ttf file:
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use:[ { loader: "url-loader", options: {limit: 10000, mimetype: 'application/octet-stream'} }]
},
font-awsome will also require loader for woff file:
{
test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/,
use:[ { loader: "url-loader", options: {limit: 10000, mimetype: 'application/font-woff'} }]
},

serve webpack bundle in express?

I am trying to introduce myself in webpack, this is my config server.js file:
const app = webpack({
devtool: 'source-map',
entry: ['whatwg-fetch', path.resolve(__dirname, 'js', 'app.js')],
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel-loader',
test: /\.js$/,
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
}
],
},
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/public/'
},
devtool: "source-map",
plugins: [
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true,
compress: {
warnings: false
}
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.LoaderOptionsPlugin({
debug: true
})
]
});
I want to serve the files to express, this is the code:
// Serve static resources
app.use('/', express.static(path.resolve(__dirname, 'public')));
app.listen(APP_PORT, () => {
console.log(`App is now running on http://localhost:${APP_PORT}`);
});
but I had an error app.use is not a function. Help?