Imports and requires are not loading properly in Webpack - javascript

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!

Related

Trying to import between multiple JS files

I'm creating a Todo app and I am using webpack to bundle multiple js files. I'm having trouble importing my functions and classes between the different js files. I keep receiving the error "SyntaxError: cannot use import statement outside a module.". I have set the entry in the webpack.config.js file to the index.js file. I can import from all the other js files into the index.js file and it works. Where I am having trouble is importing between all the js files themselves. I am fairly new to webpack and any help would be greatly appreciated. Thanks!
This is the task.js file code that I am trying to import into the ui.js file.
import { v4 as uuidv4 } from 'uuid';
export class Task {
constructor(title, description, dueDate) {
return Object.assign(this, { id: uuidv4(), title, description, dueDate, completed: false })
}
}
Here is the code in the ui.js file
import { Task } from './task.js';
const taskOne = new Task('Hello', "goodbye")
console.log(taskOne);
Here is the webpack.config.js file
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
assetModuleFilename: '[name][ext]'
},
devtool: 'source-map',
devServer: {
static: {
directory: path.resolve(__dirname, 'dist')
},
port: 3000,
open: true,
hot: true,
compress: true,
historyApiFallback: true
},
module: {
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpg|jpeg|svg|gif)$/i,
type: 'asset/resource'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Todo App',
filename: 'index.html',
template: './src/template.html'
})
]
}

export 'default' was not found when I try to import my webpack library

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?

Webpack can't extract boostrap.css with min-css-extract plugin

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 .

Webpack Hot Module Replacement still requires full refresh even after setting up

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

Sass loader not loading style

Webpack is slick... If only I could get it to work. I have two files.
App.js
App.scss
I want to import the styles from App.scss and use them in App.js
Here is my code.
// App.js
import React, {Component} from 'react';
import s from './App.scss';
class App extends Component {
render() {
return (
<div className={s.app}>
</div>
);
}
}
console.log('what is in s ' + JSON.stringify(s));
export default App;
And Sass file.
// App.scss
.app {
width: 100%;
height: 100%;
background-color: blue;
}
Console shows that s is an empty object. I would expect to see {app: ...}.
Weback is setup like this.
// webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: [
'./src/client',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, 'src')
}]
},
devServer: {
contentBase: './dist',
hot: true
}
};
No errors from webpack. No errors in the console.
After much searching I found this Github issue. Solution is to change this line in webpack.config.js
loaders: ['style', 'css', 'sass']
to
loader: 'style!css?modules!sass'

Categories

Resources