JS: install external package through webpack? - javascript

I am working on a fully JS app and trying to use an external library ( https://github.com/soldair/node-qrcode ) . My current webpack.config.js is the following:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const inheritedConfig = require('#main/build-configs/src/webpack')
const isProd = process.env.NODE_ENV === 'production';
const currentRoot = path.join(process.cwd());
module.exports = {
...inheritedConfig,
entry: { 'entry': './src/index' },
plugins: [
...inheritedConfig.plugins,
new HtmlWebpackPlugin({
title: 'QR Code Generator',
template: path.join(currentRoot, '../../packages/shared/html-templates/index.html')
}),
!isProd && new webpack.HotModuleReplacementPlugin()
].filter(Boolean)
};
Is there a way to add the package through my webpack config?

Related

How import from webpack bundle?

I built my es6 code by webpack, but I can't import from this built file. I get "undefined"
This is my src code:
export const debugFunc = () => {
console.log('debug')
}
And there is I try to use it:
import { debugFunc } from './debugFunc'
my webpack config is very simple
const webpack = require('webpack');
module.exports = {
entry: './src/index.js',
mode: 'production',
output: {
path: __dirname + "/lib",
filename: "main.js",
},
};

Using webpack with express and ejs for frontend and/or server

I am struggling a bit to find a solution to using webpack on the both the frontend and the server part of a nodejs project.
I am building an express solution with different API endpoints and a frontend that uses EJS for templating that will use these endpoints for data handling.
Basically what I am trying to achieve is to using webpack to compile my SCSS and JS on the frontend and also a solution that will compile EJS and inject the CSS and JS bundles into the frontend.
My current server.js
const express = require('express')
const formidable = require('express-formidable');
const session = require('express-session')
const bodyparser = require('body-parser')
const app = express()
const path = require('path');
const auth = require('./app/middleware/authorization/auth')
const upload = require('./app/middleware/filehandling/upload')
app.set('port', process.env.PORT || 8080);
app.set('view engine', 'ejs')
app.set('views', path.join('views'));
app.use(session({
secret: hash.getRandomString(16),
resave: true,
saveUninitialized: true
}))
app.use(express.json())
app.use('/public', express.static(path.resolve(__dirname, 'public')));
app.use(formidable());
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//DIFFERENT ROUTES DOWN HERE
app.listen(3000, () => {
console.log('listening on port 3000')
})
My folder structure is
public
- upload/
src
- scss/
- index.js
views
- partials/
- index.ejs
- login.ejs
I have a current webpack.config.dev.js that I am using for static HTML/CSS/JS project that are building and compiling SCSS and JS into bundles.
const path = require('path');
const webpack = require('webpack');
const HTMLWebpackPlugin = require('html-webpack-plugin');
// const ExtractText = require('extract-text-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const devMode = process.env.NODE_ENV !== 'production'
const dirNodeModules = 'node_modules';
const dirAPP = path.join(__dirname, 'src/app');
const dirAssets = path.join(__dirname, 'src/assets');
const packageJson = require('./package.json')
var config = {
entry: {
bundle: path.join(dirAPP, 'index')
},
resolve: {
modules: [
dirNodeModules,
dirAPP,
dirAssets
]
},
plugins: [
new webpack.DefinePlugin({
devMode: devMode
}),
new HTMLWebpackPlugin({
template: path.join('src', 'index.html'),
inject: true
}),
new MiniCssExtractPlugin({
filename: packageJson.name + '.[chunkhash].min.css'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
sourceMap: true,
config: {
path: 'postcss.config.js'
}
},
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: 'file?=name/fonts/[name].[ext]'
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [{
loader: 'file-loader',
options: {
name: '[name]-[hash:8].[ext]',
pluginPath: dirAssets + '/images/',
outputPath: dirAssets + '/images/'
}
}]
}]
}
}
module.exports = config;
And a webpack.config.build.js
const path = require('path');
const merge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpackConfig = require('./webpack.config');
const packageJson = require('./package.json');
module.exports = merge(webpackConfig, {
devtool: 'source-map',
output: {
path: path.join(__dirname, 'dist'),
filename: packageJson.name + '.[chunkhash].js'
},
plugins: [
new CleanWebpackPlugin(['dist'])
]
});
Which I call using
"dev": "cross-env NODE_ENV=dev webpack-dev-server --progress --mode development --config webpack.config.dev.js",
"build": "webpack -p --progress --mode production --config webpack.config.build.js"
I am a bit unsure how I can achieve this.

Refused to execute script from bundle.js because its MIME type

Hello I'm new to react and I'm trying to attach express framework with react, I followed this tutorial: https://blog.hellojs.org/setting-up-your-react-es6-development-environment-with-webpack-express-and-babel-e2a53994ade but when I run the server I'm getting the following error:
Failed to load resource: the server responded with a status of 404
(Not Found) localhost/:1
Refused to execute script from
'http://localhost:3000/dist/bundle.js' because its MIME type
('text/html') is not executable, and strict MIME type checking is
enabled.
I have been searching this error for two days now and I haven't find a solution. I think the problem is that the bundle.js is not being created by webpack, I would like to now why is this happening
My project directory is the following:
My config webpack file:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: './client/index.js',
output: {
path: __dirname,
filename: 'bundle.js',
publicPath: '/client/assets/'
},
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
include: path.join(__dirname, 'client'),
exclude: /node_modules/,
query: {
presets: ['es2015', 'react', 'stage-0']
}
},
{
test: /\.css$/,
loader: 'css-loader'
}
]
},
};
server.js, where I create the express instance:
const path = require('path')
const express = require('express')
module.exports = {
app: function () {
const app = express();
const indexPath = path.join(__dirname, 'indexDep.html');
const publicPath = express.static(path.join(__dirname, '../dist'));
app.use('/dist', publicPath);
app.get('/', function (_, res) { res.sendFile(indexPath) });
return app;
}
}
And app.js, where I'm running the server:
const Server = require('./server.js')
const port = (process.env.PORT || 3000)
const app = Server.app()
if (process.env.NODE_ENV !== 'production') {
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const config = require('../webpack.dev.config.js')
const compiler = webpack(config)
app.use(webpackHotMiddleware(compiler))
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPathdist
}))
}
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
Try this:
// server.js
"use strict"
const path = require('path')
const express = require('express')
module.exports = {
app(init) {
const app = express()
const indexPath = path.join(__dirname, 'indexDep.html')
const publicPath = express.static(path.join(__dirname, '../dist'))
if (init != null) init(app)
app.use('/dist', publicPath)
app.get('/', function (_, res) { res.sendFile(indexPath) })
return app
},
}
// app.js
const Server = require('./server.js')
const port = (process.env.PORT || 3000)
Server.app(app => {
if (process.env.NODE_ENV !== 'production') {
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const config = require('../webpack.dev.config.js')
const compiler = webpack(config)
app.use(webpackHotMiddleware(compiler))
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPathdist
}))
}
})
.listen(port)
console.log(`Listening at http://localhost:${port}`)
Specifically, what this does is two-fold:
It punts your initialization to before Express finally reads its catch-all routes for /dist and /. If you add the middleware after, you'll never see it set up in the first place.
It retains most of your other logic, without moving a lot of code. Closures are useful for that kind of thing, keeping logic where it belongs while still allowing others to let you hook into their logic.

Webpack dev middleware for all routes

I configured webpack dev middleware, when I go to index page / all works fine, otherwise page Not Found, how to make work dev server for all paths ?
const Koa = require('koa');
const webpack = require('webpack');
const devMiddleware = require('koa-webpack-dev-middleware')
const path = require('path');
const fs = require('fs');
const PORT = 3000;
const app = new Koa();
const config = require('./webpack.config');
const compiler = webpack(config);
app.use(devMiddleware(compiler, {
publicPath: config.output.publicPath,
historyApiFallback: true,
stats: { colors: true },
}));
app.listen(PORT, function () {
console.log(`Dev Server port: "${3000}"`);
});
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
devtool: 'inline-source-map',
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Output Management'
})
],
module: {
rules: [
{
test: /.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
}
}

CodeMirror does not work with React/Webpack

I'm working on some markdown editor for my react project.
I wanna use CodeMirror as the code editor, but it seems it does not working when I build it with webpack.
If be honest, CodeMirror are in the DOM-tree, textArea is hidden, but everything I see is:
and
UPD: The same code works perfect on codepen. I guess it's a problem with webpack.
some code:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor} from './components';
const rootElement = document.getElementById('root');
ReactDOM.render(<Editor />, rootElement);
components/editor.js
import React, { Component } from 'react';
import cm from 'codemirror';
require('codemirror/mode/markdown/markdown');
export class App extends Component {
componentDidMount() {
this.codeMirror = cm.fromTextArea(this.refs.editor, {mode: 'markdown'})
}
render() {
return (
<div>
<textarea ref='editor' autoComplete='off' defaultValue='default value' />
</div>
);
}
}
server.js
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var HOST = 'localhost';
var PORT = 3000;
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/app/index.html'));
});
app.listen(PORT, HOST, function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://' + HOST + ':' + PORT);
});
and webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-hot-middleware/client',
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'app')
}]
}
};
In webpack gitter chat #bebraw answered to my question:
Codemirror works with webpack but it takes some extra setup. you need
to bring some css etc. for it to render. example

Categories