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"));
});
Related
I have a problem in a vue project I have I´m in the process of breaking out components into a components library.
i get this error message when i consume components from my local components library.
Uncaught TypeError: Cannot read properties of undefined (reading 'fd')
at Function.useColors
looking where that is in the code i find this
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts
? Boolean(exports.inspectOpts.colors)
: tty__default["default"].isatty(process.stderr.fd);
}
and a litle googling later it is my understanding is that this code is debug-js for node and that other people have gotten the same error in the past. The solution in the old thread is something with babeland how to resolve modules but i do not seem to be able to find out how to do it for rollup.
Manipulating the bundled code manually so the function returns false makes the code run with no problem but i really do not want to do that
How can I fix this the right way. It seems like I miss something super basic that i for some reason cant find the answer to.
package.json
{
"name": "local-vue-components",
"version": "0.1.0",
"main": "lib/index.js",
"module": "lib/index.esm.js",
"scripts": {
"build": "rollup -c"
},
"peerDependencies": {
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2"
},
"dependencies": {
"local-library":"*"
},
"devDependencies": {
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2",
"#rollup/plugin-commonjs": "^14.0.0",
"#rollup/plugin-node-resolve": "^8.4.0",
"#rollup/plugin-json":"^5.0.1",
"#vue/compiler-sfc": "^3.0.0-rc.5",
"rollup": "^2.23.1",
"rollup-plugin-peer-deps-external": "^2.2.3",
"rollup-plugin-typescript2": "^0.27.2",
"rollup-plugin-vue": "^5.1.6",
"typescript": "^3.9.7",
"vue-template-compiler": "^2.6.11"
}
}
rollup.config.js
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "#rollup/plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import vue from "rollup-plugin-vue";
import json from "#rollup/plugin-json";
import packageJson from "./package.json";
export default {
input: "src/index.ts",
output: [
{
format: "cjs",
file: packageJson.main,
sourcemap: true
},
{
format: "esm",
file: packageJson.module,
sourcemap: true
}
],
plugins: [peerDepsExternal(), resolve(), commonjs(), typescript(),json(),vue()]
};
I realise it can also be a problem with the consuming project that uses babel and Webpack with the configs below.
babelrc.js
module.exports = function (api) {
const presets = [
'#babel/preset-env',
{
targets: {
chrome: "70"
}
}
];
return presets;
}
webpack.js
const path = require("path");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
require("#babel/register");
module.exports = {
entry: {
babelPollyfill: "#babel/polyfill",
jprApp: "./src/app/main.ts",
'
},
resolve: {
extensions: [".js", ".ts", ".json"],
mainFields: ["browser", "main"],
alias: {
vue$: "vue/dist/vue.esm.js"
}
},
module: {
rules: [
{
test: /\.(css)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].css',
}
}, {
loader: 'extract-loader'
}, {
loader: 'css-loader',
}, {
loader: 'postcss-loader',
}
]
},
{
enforce: "pre",
use: ["source-map-loader"],
test: /\.js$/
},
{
test: /\.ts$/,
use: 'ts-loader',
exclude: [/node_modules/,/__test__/]
},
{
test: /\.render\.js$/,
use: ["file-loader"]
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
}
}
]
},
output: {
publicPath: "",
filename: "[name].js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new NodePolyfillPlugin(),
]
};
So i'm pretty new to Webpack, and I finally got the webpack-dev-server running. It recompiles and refreshes page on save, and it shows changes to my JS code. But it doesn't seem to work well with my SASS or HTML files?
On a fresh start, it will show a change if I make it, but if I undo that change, it doesn't update. Looking around other posts, I tried added the "--hot" flag, and adding "inline" to my devServer in webpack config. This got it working for a style change, but won't show deleted or undone changes.
This is my package.json...
{
"name": "testproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js",
"start": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js",
"watch": "webpack --watch",
"server": "webpack-dev-server --open --hot"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"autoprefixer": "^9.7.4",
"babel-loader": "^8.0.6",
"css-loader": "^3.4.2",
"cssnano": "^4.1.10",
"file-loader": "^5.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"postcss-loader": "^3.0.0",
"sass": "^1.25.0",
"sass-loader": "^8.0.2",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.3"
}
}
This is my webpack.config...
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const isDevelopment = process.env.NODE_ENV !== 'production';
const webpack = require('webpack');
module.exports = {
entry: './src/javascript/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new MiniCssExtractPlugin({
filename: 'bundle.css'
}),
new HtmlWebPackPlugin({
template: './dist/index.html',
filename: 'index.html'
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
inline: true,
hot: true
},
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
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader',
options: {
implementation: require('sass')
}
}
]
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'images'
}
}
]
},
{
test: /\.(woff|woff2|ttf|otf|eot)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts'
}
}
]
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: !isDevelopment }
}
]
}
]
},
// Default mode is Production. Uses minifying
mode: 'development'
};
I must have something wrong or out of place?
Any help or tips would be appreciated. Will provide additional info if needed.
Thanks in advance!
I found a solution by adding "watchContentBase" to my devServer.
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
**watchContentBase: true,**
inline: true,
hot: true
}
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.
I have webpack.config.js file and added loader for each font type in individual module block but when I run yarn start
webback complied successfully with this details in terminal
f4769f9bdb7466be65088239c12046d1.eot 20.1 kB [emitted]
448c34a56d699c29117adc64c43affeb.woff2 18 kB [emitted]
fa2772327f55d8198301fdb8bcfc8158.woff 23.4 kB [emitted]
e18bbf611f2a2e43afc071aa2f4e1512.ttf 45.4 kB [emitted]
89889688147bd7575d6327160d64e760.svg 109 kB [emitted]
bundle.js 1.56 MB 0 [emitted] [big] main
favicon.ico 1.15 kB [emitted]
index.html 605 bytes [emitted]
and page open in the browser with bootstrap css applied on it BUT in the console, it gives multiple errors for woff woff2 and ttf file ( see image)
Module parse failed: Unexpected character '' (1:4)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
package.json
"dependencies": {
"bootstrap": "^3.3.7",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.5",
"history": "^4.7.2",
"html-webpack-plugin": "^2.30.1",
"less": "^2.7.3",
"less-loader": "^4.0.5",
"path": "^0.12.7",
"postcss-loader": "^2.0.8",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^5.0.6",
"react-redux-form": "^1.16.0",
"react-router-dom": "^4.2.2",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0",
"style-loader": "^0.19.0",
"svg-inline-loader": "^0.8.0",
"uglifyjs-webpack-plugin": "^1.0.1",
"url-loader": "^0.6.2",
"webpack-combine-loaders": "^2.0.3"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.2",
"babel-loader": "^7.1.2",
"babel-plugin-transform-es2015-destructuring": "^6.23.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"eslint": "^4.10.0",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-flowtype": "^2.39.1",
"eslint-plugin-html": "^3.2.2",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.4.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.4"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server"
}
webpack.config.js
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // eslint-disable-line
const path = require('path');
const combineLoaders = require('webpack-combine-loaders');
const BUILD_DIR = path.resolve(__dirname, 'build');
const APP_DIR = path.resolve(__dirname, 'src');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
favicon: './src/assets/favicon.ico',
inject: 'body'
});
// const extractPluginConfig = new ExtractTextPlugin({filename:'style.css', disable: false, allChunks: true});
module.exports = {
context: __dirname,
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
APP_DIR + '/index.jsx',
],
output: {
publicPath: '/',
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?/,
loader: 'babel-loader',
include: path.join(__dirname, 'src'),
exclude: /(node_modules|bower_components)/,
query: { presets: ["env", "react"] }
},
{
test: /\.css$/,
// exclude: /node_modules/,
loader: 'style-loader!css-loader?importLoaders=1'
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass?sourceMap')
},
{
test: /\.less$/,
loader: 'style-loader!css-loader!postcss-loader!less-loader'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.png$/,
loader: "url-loader",
query: {
limit: 100000
}
},
{
test: /\.jpg$/,
loader: "url-loader"
},
{
test: /\.svg(\?.*)?$/,
loader: "url-loader",
query: {
limit: 10000,
mimetype: 'image/svg+xml'
}
},
{
test: /\.(woff2?)(\?.*)?$/,
loader: "url-loader",
query: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
{
test: /\.(ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
mimetype: 'application/octet-stream'
}
},
{
test: /\.eot(\?.*)?$/,
loader: 'file-loader'
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.less', '.json']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}
}),
// new UglifyJsPlugin(), for production server only
HtmlWebpackPluginConfig
],
devServer: {
historyApiFallback: true,
hot: true
}
}
index.jsx
import 'bootstrap/dist/css/bootstrap.css'
what I have tried various comibinations in place of above modules for loaders from github solution but none of them is working, see the trials
trial 1 ( using file loader)
{
test: /\.(jpg|png|woff|woff2|eot|ttf|svg)$/,
loader: 'file-loader?name=[path][name].[ext]?[hash]'
}
trial 2 ( using url loader)
{
test: /\.(woff(2)?|eot|ttf|otf)(\?[a-z0-9]+)?$/,
loader: 'url-loader?limit=100000'
}
trial 3 (using url loader with lower limit)
{
test: /\.(woff2?|ttf|eot|svg|png|jpe?g|gif)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=8192'
},
In webpack 4, you need:
{
test: /\.(woff|woff2|ttf|eot)$/,
use: 'file-loader?name=fonts/[name].[ext]!static'
}
eg use file-loader.
there is my config about fonts
{
test: /\.(woff|woff2|ttf|eot)$/,
use: 'file?name=fonts/[name].[ext]!static'
}
maybe is useful
--- added ---
resolve: {
extensions: ['.js', '.jsx', '.css', '.less', '.json'],
modules: ['node_modules', 'path/to/your/static_resource']
}
I installed a vue plugin in a project that i'm working and i was getting this error to.
I tried to follow the instructions, but i do not know it they are outdated. I'm sharing my solution. In webpack.config.js i added the following set:
module: {
rules: [
... --> other existing rules
{
test: /\.(woff|woff2|ttf|eot)$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]!static'
},
include: /node_modules/
}
]
}
I am using vue cli webpack and below code fixed the error
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
}
I am doing React/Redux and also got this error.
I added this line in my webpack.config.dev.js to solve the issue:
module: {
loaders: [
...,
{test: /\.png$/, loader: 'file'} // Line added
]
}
Then in my R/R codes, I used import (ES6) to require the image. Then I do:
<img src={myPNGImage} .../>
In PWA studio for Magento2 ,
You can add a line in webPackConfig.js as follows
config.module.rules.push({ test: /\.(woff|woff2|ttf|eot)$/, use: 'file-loader' });
This should do the job.
The accepted answer worked for me, however since webpack 4 the answer needs a slight update to use file-loader instead of just file, e.g.:
{
test: /\.(woff|woff2|ttf|eot)$/,
use: 'file-loader?name=fonts/[name].[ext]!static'
}
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.