I'm trying to setup vue app using webpack.
This is my webpack.config.js file:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
"Shared/global": './ClientApp/src/js/Shared/global.js',
},
output: {
filename: 'js/[name].entry.js',
path: path.resolve(__dirname, 'dist'),
publicPath: ""
},
devtool: 'source-map',
mode: 'development',
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader'],
},
{
test: /\.(eot|woff(2)?|ttf|otf|svg)$/i,
type: 'asset'
},
{
test: /\.js$/,
use: {
loader: "babel-loader",
},
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "css/[name].css"
})
]
};
And this is the entry file:
import {createApp} from 'vue';
import { createStore } from 'vuex'
const _ = require('lodash')
In my layout.html I call global.entry.js as such:
<body>
<div id="layoutApp">
<h1>HELLO</h1>
</div>
</body>
<script type="module" src="/dist/js/Shared/global.entry.js" defer></script>
<script src="/ClientApp/src/js/Shared/layout.js" defer></script>
Then I try to use vue in layout.js:
const layoutApp = createApp({
mounted(){
console.log("layout is mounted VUE")
},
});
layoutApp.mount("#layoutApp")
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
But in chrome console it said createApp is not defined. But if I run only lodash code, lodash works fine. I cant figure out what I did wrong. Any help would be very helpful
Related
This is my source code ./source/client/main.jsx.
export default {
test: () => console.log('Flow')
};
And this is my webpack.config.cjs.
const path = require('path');
const webpack = require('webpack');
const packageJSON = require('./package.json');
module.exports = (env, argv) => {
return {
mode: 'development',
entry: './source/client/main.jsx',
// entry: './main.js',
output: {
path: path.join(__dirname, 'release'),
filename: 'main.js',
library: {
name: packageJSON.name,
type: 'umd'
}
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react'
],
plugins: [
'#babel/plugin-transform-runtime'
]
}
}
}
]
}
};
};
My package.json contains a list of dependencies and both main and module pointing to the webpack product.
"main": "./release/main.js",
"module": "./release/main.js",
However, when I try to import my module in another webpack project, I get the default was not found error.
import Test from 'test';
export 'default' (imported as 'Test') was not found in 'test' (module has no exports)
Am I building the module wrong?
I have a react application that I'm trying to extract the css into separate files but I'm having some issues here. I'm suing the MiniCssExtractPlugin for this. My current webpack configuration included below works fine when I include my own css files but it fails when I include my bootstrap.css from node_modules.
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import MyApp from './scenes/MyApp/MyApp'
import 'bootstrap/dist/css/bootstrap.css'
import './index.css'
import './assets/stylesheets/scenes.scss'
ReactDOM.render(<MyApp />, document.getElementById('root'))
webpack.config.js
const appConstants = function() {
switch (process.env.NODE_ENV) {
case 'local':
const localConfig = require('./config/local');
return localConfig.config();
case 'development':
const devConfig = require('./config/development');
return devConfig.config();
case 'production':
default:
const prodConfig = require('./config/production');
return prodConfig.config();
}
};
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const htmlWebpackPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
hash: true
});
let webpackConfig = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(css|scss)$/,
exclude: [/node_modules/],
include: [/node_modules\/bootstrap\/dist/],
use: [
{
loader: process.env.NODE_ENV !== 'local' ? MiniCssExtractPlugin.loader : 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(pdf|jpg|png|gif|svg|ico)$/,
exclude: [/node_modules/],
use: [
{
loader: 'file-loader'
},
]
},
{
test: /\.(woff|woff2|eot|ttf|svg|otf)$/,
exclude: [/node_modules/],
use: {
loader: 'url-loader?limit100000'
}
}
]
},
entry: [ "#babel/polyfill", "./src/index.js"],
output: {
publicPath: appConstants().DS_BASENAME ? JSON.parse(appConstants().DS_BASENAME) : '/'
},
optimization: {
splitChunks: {
chunks: 'all'
}
},
plugins: [
htmlWebpackPlugin,
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /en/),
new BundleAnalyzerPlugin({
analyzerMode: 'disabled',
generateStatsFile: true,
statsOptions: { source: false }
}),
new webpack.DefinePlugin({
'process.env': appConstants()
}),
new webpack.EnvironmentPlugin(['NODE_ENV']),
new MiniCssExtractPlugin({
filename: (process.env.NODE_ENV == "local") ? "[name].css" : "[name].[hash].css",
chunkFilename: (process.env.NODE_ENV == "local") ? "[id].css" : "[id].[hash].css"
}),
new OptimizeCSSAssetsPlugin()
],
devServer: {
historyApiFallback: true,
port: 9090
},
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
};
// configure source map per-env
if (process.env.NODE_ENV === 'local') {
webpackConfig.devtool = 'eval-source-map';
} else {
webpackConfig.devtool = 'hidden-source-map';
}
module.exports = webpackConfig;
Here is the error I get during build:
ERROR in ./node_modules/bootstrap/dist/css/bootstrap.css 7:0
Module parse failed: Unexpected token (7:0)
You may need an appropriate loader to handle this file type.
| * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
| */
:root {
| --blue: #007bff;
| --indigo: #6610f2;
That error makes me think I'm missing the proper loader but I don't know what other loader I would need for this.
TL;DR
I want to extract all my css files including bootstrap.css into a separate file from my main.js .
I got my webpack Hot Module Replacement working. I was told that once it is working, I would no longer have to do a full refresh for my code. This is not the case! I still require a refresh when I make changes to my code! (App.js).
How can I properly enable webpack HMR?
Link to the project on github
This is my entry point
import './styles/index.css';
import App from './components/App';
import React from 'react';
import { render } from 'react-dom';
const rootDOMNode = document.getElementById('app');
function renderRoot() {
render(<App/>, rootDOMNode);
}
renderRoot();
if (module.hot) {
module.hot.accept('./components/App', () => {
console.log('Accepting the updated module');
renderRoot();
});
}
webpack.config.js:
const webpack = require("webpack");
const path = require("path");
const CleanWebpackPlugin = require( "clean-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: [
"./app/index"
],
devtool: "inline-source-map",
output: {
path: path.resolve(__dirname, "dist"), // Note: Physical files are only output by the production build task `npm run build`.
publicPath: "/",
filename: "bundle.js"
},
devServer: {
contentBase: path.resolve(__dirname, "dist"),
hot: true,
port: 3000,
open: true,
compress: true
},
plugins: [
new ExtractTextPlugin({
disable: false,
filename: "css/style.css",
allChunks: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
module: {
rules: [
{ test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
} },
// { test: /(\.css)$/, use: ["style-loader", "css-loader"] },
{ test: /(\.css)$/, use: ExtractTextPlugin.extract(["css-loader"]) },
{ test: /\.(png|svg|jpg|gif)$/, use: ["file-loader"] },
// for fonts
{ test: /\.(woff|woff2|eot|ttf|otf)$/, use: ["file-loader"] }
]
}
};
The reason it is not working is because you have to re-require your app once you get the hot update, otherwise you are just re-rendering your original app.
the following code should work:
import './styles/index.css';
//import App from './components/App';
import React from 'react';
import { render } from 'react-dom';
const rootDOMNode = document.getElementById('app');
let App;
function renderRoot() {
App = require('./components/App').default; // we have to re-require this every time it changes otherwise we are rendering the same old app.
render(<App/>, rootDOMNode);
}
renderRoot();
if (module.hot) {
module.hot.accept('./components/App', () => {
console.log('Accepting the updated module');
renderRoot();
});
}
I use hot reloading with webpack-dev-server by adding a script in package.json.
webpack-dev-server --output-public-path=/dist/ --inline --hot
I have a vue project and installed waypoints
npm install waypoints
I try to import it
import waypoint from 'waypoints';
but get an error
Error: Can't resolve 'waypoints' in /Mypath
What am I doing wrong?
var webpack = require('webpack');
var path = require('path');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
var WebpackNotifierPlugin = require('webpack-notifier');
var fs = require('file-system');
var CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
/*node: {
fs: "empty"
},*/
resolve: {
alias: {
'masonry': 'masonry-layout',
'isotope': 'isotope-layout'
}
},
entry: './main.js',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, './public/assets'),
filename: 'bundle.[chunkhash].js',
},
module: {
rules: [
{ test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader?presets[]=es2015",
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: [{loader:'css-loader?sourceMap'}, {loader:'sass-loader', options: {
sourceMap: true,
}}],
})
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
]
},
plugins: [
new CleanWebpackPlugin(['assets/*', 'css/*'], {
root: '/Users/LEITH/sites/laravelleith/public',
verbose: true,
dry: false,
exclude: ['360lockturret.jpg'],
watch: true
}),
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('app.[chunkhash].css'),
new WebpackNotifierPlugin(),
function() {
this.plugin('done', stats =>{
fs.writeFileSync(
path.join(__dirname, 'manifest.json'),
JSON.stringify(stats.toJson().assetsByChunkName)
)
});
}
]
};
Waypoints comes bundled in several flavours, even via NPM, but I couldn't work out if there's a default implementation or not. So that's why your typical import Waypoint from 'waypoints' directive doesn't work.
I resolved this for my "vanilla ES6 + Webpack" setup as follows:
import 'waypoints/lib/noframework.waypoints.min.js';
const waypoint = new Waypoint({
element: document.getElementById('myScrollTarget'),
handler: () => {}
});
Basically #markedup is right, waypoints comes with various flavours, after installing waypoints if you look into /waypoints/lib/ folder you will see zepto|jquery|noframework.waypoints.js .
In this case you would require to import it as full path i.e.
import 'waypoints/lib/noframework.waypoints.min.js';
or
window.waypoint = require('waypoints/lib/noframework.waypoints');
I am using Vue with Webpack, but I when I import or require another file to be included into my main document, the file seems to have loaded, as in it doesn't give me any errors, but the imports within the files do not load, and I can't use any variables from the files. For example, I have this main document:
import './bootstrap';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
let Default = Vue.component('Default', {
template: `
<li>
This is home
</li>
`
});
let About = Vue.component('About', {
template: `
<li>
This is about us maaan
</li>
`
});
var router = new VueRouter({
routes: [
{ path: '/', component: Default },
{ path: '/about', component: About }
]
})
require('./sass/styles.scss');
new Vue({
el: '#app',
router: router
})
...and my bootstrap file is simply:
import Vue from 'vue';
import axios from 'axios';
I get the following error: Uncaught ReferenceError: Vue is not defined, as if the file had not been included. If I make any changes to the path, I get a file not found error, so I imagine that the file is located. the same for any variables in the file, they are not available in the main file afterwards. This is my webpack.config.js:
var path = require('path')
var webpack = require('webpack')
var inProduction = (process.env.NODE_ENV === 'production');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: 'dist/',
filename: 'build.js'
},
module: {
rules: [
{
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: 'images/[name].[ext]?[hash]'
}
},
{
test: /\.s[ac]ss$/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader'],
fallback: 'style-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'styles.css',
disable: process.env.NODE_ENV === "development"
})
],
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: 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
})
])
}
Many thanks!