The page loads up correctly and even logs to client console [WDS] Hot module replacement enabled. But when I make changes to files nothing is reflected on the page. Even on reload. Only when restarting the server.
Not sure if this matter but Im using redux.
webpack.config.js
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'eval-source-map',
entry: __dirname + '/src/index.js',
output: {
path: __dirname + '/build',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.css$/,
loader: 'style!css?modules!postcss'
},
{
test: /\.(png|jpg|jpeg|gif|woff)$/,
loader: 'url-loader?limit=8192'
}
]
},
postcss: function() {
return [autoprefixer, precss];
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname + '/src/index.html'
}),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './public',
colors: true,
historyApiFallback: true,
inline: true,
hot: true
},
jest: {
moduleFileExtensions: ["js", "jsx"]
}
};
.babelrc
{
"presets": ["react", "es2015", "stage-0"],
"env": {
"development": {
"plugins": [["react-transform", {
"transforms": [{
"transform": "react-transform-hmr",
"imports": ["react"],
// this is important for Webpack HMR:
"locals": ["module"]
}]
// note: you can put more transforms into array
// this is just one of them!
}]]
}
}
}
Try adding
"scripts": {
"start": "node_modules/.bin/webpack-dev-server --progress --inline"
},
in your package.json file, and use npm start.
adding additional entry point in webpack config will reload the page automatically, however you will loose all the state because of a refresh.
entry: [
'webpack-hot-middleware/client?reload=true',
__dirname + '/src/index.js',
],
and in server js
app.use(require('webpack-hot-middleware')(compiler));
Related
I have two main directories in my project: "src" and "specs".
The entrypoint of my webpack configuration is set to a file within src. Also the context of the webpack config is set to the src directory. I have a postinstall hook in my package.json which bundles the app into a dist folder whenever the package is installed via "npm install". This also means that the devDependencies are not installed and that is what causes my npm install to fail. Apparently webpack tries to process the files in specs which it cannot do because the devDependencies are not installed.
Any idea why webpack thinks it should process the files in the specs directory?
Here is my complete webpack config:
const path = require("path");
const nodeExternals = require("webpack-node-externals");
const NODE_ENV = "development";
const client = {
entry: path.join(__dirname, "src", "browser_sdk", "index.ts"),
context: path.resolve(__dirname, "src", "browser_sdk"),
target: "web",
mode: NODE_ENV,
devtool: "source-map",
watch: false,
output: {
path: path.resolve(__dirname, "dist"),
filename: "client.js",
library: {
type: "umd",
},
},
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader",
exclude: /node_modules.*\.js$/,
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
externals: {
"pg-native": "require('pg-native')"
},
optimization: {
minimize: false,
},
};
const server = {
entry: path.join(__dirname, "src", "server", "index.ts"),
context: path.resolve(__dirname, "src", "server"),
mode: NODE_ENV,
target: "node",
externals: [nodeExternals(), 'pg-native'],
watch: false,
devtool: "source-map",
output: {
path: path.resolve(__dirname, "dist"),
filename: "server.js",
library: {
type: "umd",
},
},
resolve: {
extensions: [".ts", ".js"],
},
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader",
exclude: /node_modules.*\.js$/,
},
],
},
};
module.exports = [server, client];
The following config fixed my problems. I used transpileOnly to prevent the specs directory is bundled and I wrote a custom exclude handler to prevent node_module is bundled.
module: {
rules: [
{
test: /\.tsx?$/,
use: {
loader: "ts-loader",
options: {
transpileOnly: true
},
},
exclude: (e) => {
let file = e.replace(__dirname, '.');
return file.match(/node_modules/)
}
},
],
},
I have a problem with building my vuejs app on heroku after using my webpack config instead of simple using vue-cli-service build
package.json
"build": "webpack --config webpack.config.js",
//before webpack I use this
//"build": "vue-cli-service build",
after build with webpack my heroku build the whole app properly and I have this:
remote: -----> Compressing...
remote: Done: 92.6M
remote: -----> Launching...
remote: Released v69
remote: https://someapp.herokuapp.com/ deployed to Heroku
but when i go to https://someapp.herokuapp.com/, my app is blank and I have 403 Forbidden nginx :/
I do not know what is wrong with my webpack :/
here is my webpack config
webpack.config.js
var path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
entry: './src/main.js',
mode: 'production',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'someapp.bundle.js'
},
optimization: {
usedExports: true,
minimize: true,
minimizer: [new UglifyJsPlugin()],
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: 'someapp.bundle.css'
}),
new OptimizeCSSAssetsPlugin(),
new CompressionPlugin({
test: /\.js(\?.*)?$/i,
algorithm: "gzip",
filename: "[path][base].gz"
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
},{
test: /\.vue$/,
loader: 'vue-loader'
},{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader?name=./fonts/[name].[ext]'
},{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader?name=./fonts/[name].[ext]'
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader?name=./img/[name].[ext]'
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader?name=./img/[name].[ext]'
}, {
test: /\.jpg$/,
use: ["file-loader?name=./img/[name].[ext]"]
}, {
test: /\.png$/,
use: ["file-loader?name=./img/[name].[ext]"]
}]
},
resolve: {
alias: {
'#': path.resolve('src')
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: false
}
#EDIT:
I change build to vue-cli-service build and whole app was created successfully and a I do not have 403:Forbidden, so, problem must be with webpack
can someone tell me what is wrong with my heroku build?
thanks for any help!
I have a webpack configuration that generates the react bundle when i call webpack directly.
Since i would like to incorporate hot reloading i need to run the webpack dev server alongside my development express server (serving API endpoints) that runs on port 3000
webpack.dev.config.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const Jarvis = require('webpack-jarvis');
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = merge({}, {
mode: 'development',
devtool: 'cheap-module-eval-source-map',
output: {
chunkFilename: '[name]-[hash].js',
publicPath: "http://localhost:3000/build/",
crossOriginLoading: 'anonymous'
},
optimization: {
noEmitOnErrors: true,
namedModules: true,
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new HtmlWebpackPlugin({
inlineSource: '.(js|css)$',
inject: 'head',
filename: path.join(__dirname, "/dist/index.html"),
template: path.join(__dirname, "/public/index.html"),
chunks: ['common', 'main']
}),
new Jarvis({port: 7003}),
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
_DEVELOPMENT_: true,
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: { presets: ["es2015", "react", "stage-0"] }
}
},
{
test: /\.jsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: { presets: ["es2015", "react", "stage-0"] }
}
},
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: ["file-loader"]
},
{
test: /\.svg$/,
use: {
loader: "svg-inline-loader"
}
},
{
test: /\.ts$/,
use: [
{
loader: "ts-loader",
options: {
compilerOptions: {
declaration: false,
target: "es5",
module: "commonjs"
},
transpileOnly: true
}
}
]
}
]
},
resolve: {
alias: {
'react-dom': '#hot-loader/react-dom'
}
},
entry: {
main: [
'babel-polyfill',
'react-hot-loader/patch',
'webpack/hot/only-dev-server',
'webpack-dev-server/client?https://0.0.0.0:7001',
'./src/index.jsx',
],
}
});
dev-server.js
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.dev.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
headers: {'Access-Control-Allow-Origin': '*'},
hot: true,
https: true,
clientLogLevel: 'error',
overlay: true,
historyApiFallback: true,
disableHostCheck: true,
watchOptions: {
ignored: /\/node_modules\/.*/,
},
stats: {
assets: false,
cached: false,
cachedAssets: false,
children: false,
chunks: false,
chunkModules: false,
chunkOrigins: false,
colors: true,
depth: false,
entrypoints: true,
excludeAssets: /app\/assets/,
hash: false,
maxModules: 15,
modules: false,
performance: true,
reasons: false,
source: false,
timings: true,
version: false,
warnings: true,
},
}).listen(7001, '0.0.0.0', function(err, result) {
console.log(`Serving chunks at path ${config.output.publicPath}`);
});
package.json scripts
"scripts": {
"build": "webpack --config webpack.dev.config.js --progress --profile --colors",
"start-dev": "node dev-server.js",
"build-prod": "webpack --config webpack.prod.js --progress --profile --colors",
"start": "node server.js"
},
If i run
npm run build
The result is a new js bundle and html:
dist/main.js
dist/index.html
however the ideal situation is to run
npm run start-dev
which will start the dev server, this outputs that is has successfully built the bundles, but they never appear in my filesystem so there must be an output config that i have not setup correctly in the dev server?
EDIT
Issue turned out to be as described by the post below.
To access the live bundle reloads i edited the bundle public path from the "production server" back to just the build location, and then accessed the page from the devserver instead of the page being served by the "production server"
output: {
chunkFilename: '[name]-[hash].js',
publicPath: "/build/",
crossOriginLoading: 'anonymous',
path: path.join(__dirname, "/dist"),
},
Webpack dev-server don't write your changes to the disk every time you change your source code. Instead, it watches your files change, process it and serve from memory. Check out here as it explains in detail.
I am currently using:
"mocha": "^5.2.0"
"mocha-webpack": "^2.0.0-beta.0"
"webpack": "^4.19.1"
"nyc": "^13.0.1"
and for some reason, I'm getting weird source files.
.tmp/mocha-webpack/1537879911832/webpack:/src
| 61.18 | 29.63 | 64.29 | 61.18 | |
db.js
I'm wondering how this is generated because exclude doesn't work
"nyc": {
"exclude": [
"./tmp/**/*"
],
}
Here's my webpack file
var nodeExternals = require("webpack-node-externals")
const path = require("path")
const webpack = require("webpack")
const webpackConfig = {
mode: "none",
context: path.resolve(__dirname),
resolve: {
extensions: [".js"],
alias: {
"#": path.join(__dirname, "../src"),
}
},
output: {
// use absolute paths in sourcemaps (important for debugging via IDE)
devtoolModuleFilenameTemplate: "[absolute-resource-path]",
devtoolFallbackModuleFilenameTemplate: "[absolute-resource-path]?[hash]"
},
devtool: "inline-cheap-module-source-map",
plugins: [
new webpack.NamedModulesPlugin()
],
target: "node", // webpack should compile node compatible code
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
}
module.exports = webpackConfig
I got it working by reading this manual: https://github.com/vuejs/vue-test-utils-mocha-webpack-example
The main trick was to install babel-plugin-istanbul and update .babelrc file:
"env": {
"test": {
"plugins": ["istanbul"]
}
}
And package.json looks like:
"nyc": {
"exclude": [
"**/tests/**/*.js",
".tmp/**/*.js",
"webpack.config.js"
]
}
And the webpack.config.js looks like:
var path = require('path')
var webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
module.exports = {
entry: './src/main.js',
output: {
// use absolute paths in sourcemaps (important for debugging via IDE)
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]',
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, 'src')
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
devServer: {
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
devtool: 'inline-cheap-module-source-map',
externals: ["fs", nodeExternals()],
mode: 'development',
plugins: [
new webpack.NamedModulesPlugin()
]
}
I use webpack and livereload plugin but when I change something in styles, page refresh but I don't want it.
When I use gulp, I change anything in styles and save it and then css reload without page refresh.
Why does not work like gulp on webpack?
Codes are below
webpack.config.js
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const WebpackNotifierPlugin = require("webpack-notifier");
const webpack = require("webpack");
const LiveReloadPlugin = require("webpack-livereload-plugin");
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: [
"./resources/js/app.jsx",
"./resources/scss/app.scss",
],
devtool: "source-map",
output: {
path: path.resolve(__dirname, "public/assets"),
filename: "js/app.js",
publicPath: "/public/assets/"
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react", 'stage-2']
}
}
}, {
test: /\.(scss)$/,
loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader', "postcss-loader"])
}]
},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
watch: true,
plugins: [
new CopyWebpackPlugin([{
from: "node_modules/bootstrap/dist",
to: "plugins/bootstrap"
}, , {
from: 'node_modules/font-awesome/css',
to: 'plugins/font-awesome/css',
}, {
from: 'node_modules/font-awesome/fonts',
to: 'plugins/font-awesome/fonts',
}]),
new WebpackNotifierPlugin({
alwaysNotify: true
}),
new webpack.LoaderOptionsPlugin({
debug: true
}),
new LiveReloadPlugin(),
new ExtractTextPlugin({
filename: 'css/app.css'
}),
new Dotenv({
path: './.env',
safe: true
}),
new webpack.EnvironmentPlugin(['NODE_ENV'])
],
node: {
fs: "empty"
}
};
package.json
"scripts": {
"start": "webpack-dev-server --history-api-fallback --progress --colors",
"dev": "cross-env NODE_ENV=development webpack --progress --color",
"prod": "cross-env NODE_ENV=production webpack -p --progress --color"
},
I use "npm run dev" command.
Where is the problem ?
ExtractTextPlugin sadly doesn't support hot module replacement.
From the page plugin description:
No Hot Module Replacement
what you need to do is use the plugin just in production.
rules: [
...
{
test: /\.scss$/,
use: process.env.NODE_ENV === 'production' ?
ExtractTextPlugin.extract([
"css-loader", "sass-loader", "postcss-loader"
]) : [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" },
{ loader: "postcss-loader" }
]
}
]
Try like this it will work.
{
test: /\.(s*)css$/,
loader: ExtractTextPlugin.extract(['style-loader', 'css-loader', "sass-loader"])
}
If you share the package.json than it will be helpful for others to solve the issue.