How to bundle Nunjucks files via Webpack - javascript

I have a complete site that I want to design a build tool for it.In fact, I chose Webpack for doing that. The project structure is like this:
I have nunjucks, html, css, sass and js files. I must bundle them via webpack. My webpack config file is here:
var HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const NunjucksWebpackPlugin = require('nunjucks-webpack-plugin')
module.exports = {
entry: ['./src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
writeToDisk: true
},
plugins: [
new CopyPlugin([
{ from: 'public/images', to: 'images' },
{ from: 'public/fonts', to: 'fonts' },
{ from: 'src/pages/about', to: '.' }
]),
new CleanWebpackPlugin(),
// new HtmlWebpackPlugin()
new HtmlWebpackPlugin({
title: 'Asset Management' //title of file.html
})
],
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
},
{
test: /\.(njk|nunjucks)$/,
loader: 'nunjucks-loader'
},
{
// to auto refresh index.html and other html
test: /\.html$/,
loader: 'raw-loader',
exclude: /node_modules/
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: {
interpolate: true
}
}
]
}
]
}
}
The "index.js" file also is like this:
import _ from 'lodash'
import './pages/about/about_moon.scss'
import './pages/about/about_moon.html'
var tpl = require('./pages/home/index_moon.njk')
var html = tpl.render({ message: 'Foo that!' })
function component() {
return element
}
document.body.appendChild(component())
I configured the "package.json" file and defined scripts to run webpack:
"start": "webpack-dev-server --open",
"build": "webpack"
The problem is when I run npm run build, the dist folder was made and it had a html file but there is nothing to show. I have already had some html files and wanted to bundle all of them to "bundle.js", but I have not known how. Would you please tell me how I can bundle this project?
Thank you in advance.

Problem solved. I changed the Webpack.config.js file to this:
const path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
module.exports = {
entry: ['./src/index.js', './script.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
// HtmlWebpackPluginConfig
new HtmlWebpackPlugin({
filename: 'index.html',
inject: 'head',
template: './index.njk'
}),
new CleanWebpackPlugin(),
new CopyPlugin([
{ from: 'public/images', to: 'images' },
{ from: 'public/fonts', to: 'fonts' }
])
],
module: {
rules: [
{
test: /\.exec\.js$/,
use: ['script-loader']
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.(scss)$/,
use: [
{
// Adds CSS to the DOM by injecting a `<style>` tag
loader: 'style-loader'
},
{
// Interprets `#import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')]
}
}
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader'
}
]
},
{
// HTML LOADER
// Super important: We need to test for the html
// as well as the nunjucks files
test: /\.html$|njk|nunjucks/,
use: [
'html-loader',
{
loader: 'nunjucks-html-loader',
options: {
// Other super important. This will be the base
// directory in which webpack is going to find
// the layout and any other file index.njk is calling.
// searchPaths: [...returnEntries('./src/pages/**/')]
// Use the one below if you want to use a single path.
// searchPaths: ['./']
}
}
]
}
]
}
}
Also, I wrote the script.js file like this, since, function names were changed and they could not be run after bundling.
document.getElementById('body').onload = function() {
console.log('Document loaded')
var menu = localStorage.getItem('menu')
if (menu === 'opened')
document.getElementById('navigation').classList.add('opened')
}
document.getElementById('menu-button').onclick = function() {
// localstorage used to define global variable
var menu = localStorage.getItem('menu')
localStorage.setItem('menu', menu === 'closed' ? 'opened' : 'closed')
document.getElementById('navigation').classList.toggle('opened')
}
// Window.onLoad = onLoad // global variable in js
The index.js was used to import other files and it was like this:
import _ from 'lodash'
require('../index.njk')
require('../base.html')
require('../style.css')
This is the Json file:
{
"name": "menu_moon",
"version": "1.0.0",
"description": "",
"private": true,
"dependencies": {
"browser-sync": "^2.26.7",
"extract-text-webpack-plugin": "^3.0.2",
"fast-glob": "^3.1.1",
"fs-extra": "^8.1.0",
"g": "^2.0.1",
"html-loader": "^0.5.5",
"i": "^0.3.6",
"lodash": "^4.17.15",
"mkdirp": "^0.5.1",
"nunjucks": "^3.2.0",
"nunjucks-html-loader": "^1.1.0",
"nunjucks-isomorphic-loader": "^2.0.2",
"nunjucks-loader": "^3.0.0",
"raw-loader": "^4.0.0"
},
"devDependencies": {
"browser-sync-webpack-plugin": "^2.2.2",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.5",
"css-loader": "^3.2.1",
"file-loader": "^5.0.2",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.13.0",
"nunjucks-webpack-plugin": "^5.0.0",
"sass-loader": "^8.0.0",
"script-loader": "^0.7.2",
"style-loader": "^1.0.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"scripts": {
"moon-start": "browser-sync start --server --files './**/*.*'",
"moon-build": "node build_product_moon.js",
"start": "webpack-dev-server --open",
"build": "webpack"
},
"author": "",
"license": "ISC"
}
I hope it was useful for others.

Related

Webpack 4 – simple js function not working after bundled files

I’m relatively new to webpack. I’m trying to make a simple architecture work, but can’t seem to find out what’s wrong. I’m going to try to summarize my code:
package.json file:
"devDependencies": {
"#babel/preset-env": "^7.8.3",
"babel-loader": "^8.0.6",
"babel-preset-es2015": "^6.24.1",
"bootstrap": "^4.4.1",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.2",
"file-loader": "^5.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"jest": "^24.9.0",
"jest-cli": "^24.9.0",
"jquery": "^3.4.1",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"popper.js": "^1.16.1",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1",
"webpack-merge": "^4.2.2"
}
webpack.config.js file:
"use strict";
const path = require("path");
const merge = require("webpack-merge");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
mode: "production",
devtool: "none",
entry: {
"backend":"./src/backend.src.js"
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
optimization: {
minimize: true,
concatenateModules: true,
namedModules: true,
minimizer: [
new TerserPlugin(),
new OptimizeCssAssetsPlugin()
]
},
plugins: [
new HtmlWebpackPlugin({
minify: {
collapseWhitespace: true,
removeComments: true
}
}),
new MiniCssExtractPlugin({filename: "styles-[name].bundle.css"}),
new CleanWebpackPlugin()
],
module: {
rules: [
//CSS.
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
},
//SASS.
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
//JS (transpile to es5)
{
test: /\.js$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
]
},
//HTML
{
test: /\.html$/,
use: [
"html-loader"
]
},
//Files
{
test: /\.(svg|png|jpg|jpeg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs",
esModule: false
}
}
}
]
}
};
backend.src.js file:
"use strict";
import '../app_styles/styles-backend.css';
import { webpackDebugTest } from '../app_js/functions-syncsystem.js';
functions-syncsystem.js file:
"use strict";
export function webpackDebugTest()
{
alert("Webpack test - inside function");
}
index.html file (simple, plain html where i´m importing the the bundled files in order to test):
(simple html)
<script>
webpackDebugTest();
</script>
(simple html)
When I run the index, the css file loads fine, the js file also loads fine, but it doesn´t seem to recognize the simple js function I created in order to test the architecture. Console gives me an error message like this:
Uncaught ReferenceError: webpackDebugTest is not defined
I’ve also tried changing the functions-syncsystem.js file to the following:
"use strict";
function webpackDebugTest()
{
alert("Webpack test - inside function");
}
module.exports = {
webpackDebugTest: webpackDebugTest
};
And in the bundled file, I can find the following code:
e.exports={webpackDebugTest:function(){alert("Webpack test - inside function")}
And it still returns me that same error message on the console panel.
Anyone can detect what could be the issue with my usage?
entry: {
backend:"./src/backend.src.js"
},
in order to use "import" you need to install this
npm i #babel/register --save
on top of your entry point files
require("#babel/register")

Exclude some css files in webpack

I'm facing a problem with webpack. My project has the following structure.
Folder structure:
src
js
app.js // For importing app.scss file
vendor.js // For importing vendor.scss file
scss
app.scss // Our custom styles
vendor.scss // Require all vendor styles from node_modules
package.json
postcss.config.js
webpack.config.js
Inside scss folder there are 2 files app.scss & vendor.scss. app.scss file contains all our custom styles, vendor.scss file contains all vendor styles such as bootstrap library styles.
After webpack command:
npm run dev
Webpack import these scss files through JavaScript files and add vendor prefixes via postcss-loader and output on a dist
folder.
But I don't want to add vendor prefixes on vendor.scss file because the vendor library already has vendor prefixes. So is there a way to exclude vendor.scss file from postcss-loader.
Full Code:
src/js/app.js:
import '../scss/app.scss'
src/js/vendor.js:
import '../scss/vendor.scss'
src/scss/app.scss:
// Our custom styles
.app {
display: flex;
}
src/scss/vendor.scss:
// Vendor Styles
.container {
display: flex;
}
#import '~bootstrap/scss/bootstrap';
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode development --progress true --colors"
},
"author": "",
"license": "MIT",
"dependencies": {
"bootstrap": "^4.2.1"
},
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.3.1",
"autoprefixer": "^9.4.6",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.0",
"filemanager-webpack-plugin": "^2.0.5",
"mini-css-extract-plugin": "^0.5.0",
"node-sass": "^4.11.0",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1"
}
}
postcss.config.js:
module.exports={
plugins: [
require('autoprefixer')({
'browsers': [
'>= 1%',
'last 1 major version',
'not dead',
'Chrome >= 45',
'Firefox >= 38',
'Edge >= 12',
'Explorer >= 10',
'iOS >= 9',
'Safari >= 9',
'Android >= 4.4',
'Opera >= 30'
],
cascade: true
})
]
};
webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
module.exports = function() {
return ({
entry: {
'vendor': './src/js/vendor.js',
'app': './src/js/app.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].[chunkhash].js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
}, {
loader: 'css-loader',
}, // translates CSS into CommonJS
{
loader: 'postcss-loader',
}, // Add vendor prefixes on build css file
{
loader: 'sass-loader',
} // compiles Sass to CSS
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css'
}),
// Before Build
new FileManagerPlugin({
onStart: {
delete: [
'dist',
],
}
}),
]
});
};
Zip file.
So you want vendor prefixes don't add on Webpack generated vendor.css file.
Remember Webpack parse loader array on reverse order. You could add exclude property on the object of postcss-loader with the regular expression.
webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
module.exports = function() {
return ({
entry: {
'vendor': './src/js/vendor.js',
'app': './src/js/app.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].[chunkhash].js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.s(c|a)ss$/,
use: {
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
},// Take scss file and split into a separate css file
},
{
test: /\.s(c|a)ss$/,
use: {
loader: 'css-loader',
},// Interprets scss #import and url() like import/require()
},
{
test: /\.s(c|a)ss$/,
exclude: [/vendor/],
use: {
loader: 'postcss-loader',
},
}, // PostCSS turns your SCSS file into a JS object & converts that object back to a SCSS file
{
test: /\.s(c|a)ss$/,
use: {
loader: 'sass-loader',
},// look for scss file through sass-loader, compile scss into css code
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css'
}),
// Before Build
new FileManagerPlugin({
onStart: {
delete: [
'dist',
],
}
}),
]
});
};

Style loader not loading css in my <head>

I am trying to import my css in my webpack bundle.
We are creating an angular 1 application and we are bundle it with webpack. For the moment everything was fine. The html has the bunlde and vendor scripts. Other js are been in included and the views are copied and included.
In this step we are trying to include a css file we create in a styles/ folder. For the output I guess that the css file is processed by css-loader, but the style-loader didn't include the css file in the tag.
Can anyone give me a hint?
My webpack.config in the rules is like this.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require ('webpack'); module.exports = {
mode: 'development',
entry: {
vendor: ['angular', '#uirouter/angularjs'],
app: './src/index.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: 'dist',
hot: true,
inline: true,
open:'chrome',
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management',
template: './src/index.html',
}),
new webpack.HotModuleReplacementPlugin(),
new CopyWebpackPlugin([
{
from: './src/views/**/*',
to: ''
},
], {
ignore: [],
copyUnmodified: true
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.html$/,
use: {
loader: 'html-loader',
options: {
attrs:[
':data-src'
]
}
}
}
]
}
};
My index.html is
<!doctype html>
<html>
<head>
<title>Getting Started</title>
</head>
<body>
<a ui-sref="about" ui-sref-active="active">About</a>
<ui-view></ui-view>
</body>
</html>
My index.js is like this:
import first_controller from './controllers/first_controller.js';
import uiRouter from '#uirouter/angularjs';
//import css from './styles/main.css'; // I try this also
import './styles/main.css'; //This isn't working either.
var app = angular.module ('app', ['ui.router']);
app.controller ('first_controller', first_controler);
app.config(function($stateProvider) {
var exampleState = {
name: 'example',
url: '/example',
templateUrl: './src/views/example.html', }
$stateProvider.state(exampleState );
});
my css in the folder /styles/main
.example_css {
color: red;
}
And the example view is:
<div class="example_css">Example</div>
My package.json is:
{
"name": "Example",
"version": "1.0.0",
"main": "webpack.config.js",
"scripts": {
"build": "webpack --colors",
"start": "webpack-dev-server --progress --colors --watch --inline --open"
},
"devDependencies": {
"angular": "^1.7.7",
"clean-webpack-plugin": "^2.0.0",
"copy-webpack-plugin": "^5.0.0",
"css-loader": "^2.1.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.2.1"
},
"dependencies": {
"#uirouter/angularjs": "^1.0.22"
}
}
Depending on your webpack version you want to use extract-text-webpack-plugin or mini-css-extract-plugin to put styles into a file.
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
}
To include a path to CSS file in index.html on build - see how to create templates with HtmlWebpackPlugin.

WebPack hot reload with Vue.js and .NET MVC

I'm trying to integrate Vue.js (which I'm also new to) with an existing .NET MVC project. This is so that I can give Vue a try in certain Areas of the application where I think it would be appropriate.
I have followed a couple of guides for doing this:
https://medium.com/corebuild-software/vue-js-and-net-mvc-b5cede228626
https://medium.com/#hyounoosung/integrating-vue-js-2-0-to-net-mvc5-project-f97eb5a5b3ad
It seems that everything has gone alright so far but I've noticed that the hot reloading is not working. When I run the webpack server, I can see that it's detecting the changes and recompiling the file(s) but nothing happens in the browser. Infact, nothing happens even when I manually refresh or hard-refresh the page. If I stop the application and then run it again, only then does it update.
Here's is the simple setup I have so far...
I have a new MVC Area with a single view in it with the following folder structure:
WebpackTest/Views/index.html:
<div id="app">
<h3>#ViewBag.Message</h3>
{{ vueMessage }}
</div>
#section Scripts {
<script src="~/bundle/webpacktest.js"></script>
}
I then have a scripts folder which contains my Vue code:
scripts/webpacktest/main.js
import Vue from 'vue'
new Vue({
el: '#app',
data() {
return {
vueMessage: 'Message from Vue'
}
}
})
Here is my package.json:
{
"name": "test",
"description": "test",
"version": "1.0.0",
"author": "Andy Furniss",
"license": "MIT",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
},
"dependencies": {
"eslint": "^5.9.0",
"vue": "^2.5.11"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-stage-3": "^6.24.1",
"cross-env": "^5.0.5",
"css-loader": "^0.28.7",
"file-loader": "^1.1.4",
"node-sass": "^4.5.3",
"sass-loader": "^6.0.6",
"vue-loader": "^13.0.5",
"vue-template-compiler": "^2.4.4",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1",
"eslint-plugin-vue": "^4.7.1"
}
}
...and my webpack.config.js:
var path = require('path')
var webpack = require('webpack')
var fs = require('fs')
var appBasePath = './Scripts/app/'
var jsEntries = {}
// We search for index.js files inside basePath folder and make those as entries
fs.readdirSync(appBasePath).forEach(function (name) {
var indexFile = appBasePath + name + '/main.js'
if (fs.existsSync(indexFile)) {
jsEntries[name] = indexFile
}
})
module.exports = {
entry: jsEntries,
output: {
path: path.resolve(__dirname, './wwwroot/bundle/'),
publicPath: '/wwwroot/bundle/',
filename: '[name].js'
},
module: {
rules: [
{
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: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
],
'sass': [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}
// 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: {
proxy: {
'*': {
target: 'https://localhost:44369/',
changeOrigin: true,
secure: false
},
port: 8080,
host: '0.0.0.0',
hot: true,
inline: 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
})
])
}
When I change the message in main.js, nothing happens, even if I refresh even though the webpack server is telling me things are happening.
Hot reload cannot work if you physically write files to the disk.
I created this template that combines .NET MVC with Vue.js. You can use the entire Vue ecosystem but if you don't want it on any page you can just opt out.
GitHub: https://github.com/danijelh/aspnetcore-vue-typescript-template
Medium: https://medium.com/#danijelhdev/multi-page-net-core-with-vue-js-typescript-vuex-vue-router-bulma-sass-and-webpack-4-efc7de83fea4
You can use it as an example or starting point.
add this line to startup.cs
app.Run(async (context) =>
{
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
});

After build in webpack ReactJS does't work

After webpack command webpack catch all files and finish build in dist folder, but react component doesn't work. I don't understand why. My configs attached:
package.json
{
"name": "name",
"version": "1.0.0",
"description": "Example",
"main": "index.js",
"scripts": {
"watch": "webpack --progress --watch",
"start": "webpack-dev-server --open",
"build": "webpack"
},
"devDependencies": {
"autoprefixer": "^7.1.3",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.16",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.30.1",
"node-sass": "^4.5.3",
"optimize-css-assets-webpack-plugin": "^3.1.1",
"postcss-loader": "^2.0.6",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
},
"browserslist": [
"last 15 versions",
"> 1%",
"ie 8",
"ie 7"
]
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: ['./app/app.js', './app/sass/app.sass'
],
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "postcss-loader"]
}),
},
{
test: /\.(sass|scss)$/,
use: ExtractTextPlugin.extract(['css-loader', 'postcss-loader', 'sass-loader'])
},
{
test: /\.(png|svg|jpg|gif)$/,
use: {
loader: 'file-loader',
options: {
name: 'img/[name].[ext]', // check the path
}
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: {
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]', // check the path
}
}
}
]
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Build version'
}),
new ExtractTextPlugin({
filename: 'css/app.min.css',
allChunks: true,
}),
new OptimizeCssAssetsPlugin()
]};
babel.rc
{"presets":["es2015", "react"]}
app file system:
app/
components/
fonts/
img/
sass/
app.js
index.html
index.html has a <div> with id="app" and script with src="app.js" in the body.
Move react and react-dom to dependencies instead of devDependecies in your package.json then try to build again.
Check this answer for an explanation:
Bower and devDependencies vs dependencies
Your react and react-dom packages are dependencies try moving them there.
Try modifying your webpack config file to some like this:
module.exports = {
entry: [
'./app/app.js',
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js',
publicPath: '/dist',
sourceMapFilename: 'bundle.map',
},
devtool: process.env.NODE_ENV === 'production' ? undefined : 'cheap-module-eval-source-map',
resolve: {
modules: ['node_modules', './app/components'],
extensions: ['.js', '.jsx'],
},
module: {
loaders: [
{
test: /(\.js$|\.jsx$)/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react', 'es2015'],
},
},
],
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true,
compressor: {
warnings: false,
},
})
],
};
Add other necessary rules you need to the rules array.
With this config though, you don't need the .babelrc file as everything is all in place.

Categories