How to add a new npm package with webpack? I can't understand the main idea.
Example, let's use npm install react-ripple-effect --save-dev from npm package here
After that, a bunch of files appears in /node_modules/react-ripple-effect
My structure:
>ReactApp
>>App
>>>components
----Arctic.jsx
----ArcticForm.jsx
----ArcticMessage.jsx
----Main.jsx
----Nav.jsx
>>>styles
----app.scss
---app.jsx
>>node_modules
...
>>public
---bundle.js
---index.html
--package.json
--server.js
--webpack.config.js
package.json
{
"name": "react-app",
"version": "1.0.0",
"description": "xxx",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "xxx",
"license": "xxx",
"dependencies": {
"express": "^4.14.0",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.23.1",
"foundation-sites": "^6.2.0",
"jquery": "^2.2.1",
"node-sass": "^3.4.2",
"react-ripple-effect": "^1.0.4",
"sass-loader": "^3.1.2",
"script-loader": "^0.6.1",
"style-loader": "^0.13.0",
"webpack": "^1.12.13"
}
}
webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: [
'script!jquery/dist/jquery.min.js',
'script!foundation-sites/dist/foundation.min.js',
'./app/app.jsx'
],
externals: {
jquery: 'jQuery'
},
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
})
],
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
root: __dirname,
alias: {
Main: 'app/components/Main.jsx',
Nav: 'app/components/Nav.jsx',
Arctic: 'app/components/Arctic.jsx',
ArcticForm: 'app/components/ArcticForm.jsx',
ArcticMessage: 'app/components/ArcticMessage.jsx',
applicationStyles: 'app/styles/app.scss'
},
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
}
};
app.jsx
var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Main = require('Main');
var Nav = require('Nav');
var Arctic = require('Arctic');
// Load foundation
require('style!css!foundation-sites/dist/foundation.min.css')
$(document).foundation();
// App css
require('style!css!sass!applicationStyles')
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Main}>
<IndexRoute component={Arctic}/>
</Route>
</Router>,
document.getElementById('app')
);
main.jsx
var React = require('react');
var Nav = require('Nav');
var Main = (props) => {
return (
<div>
<Nav />
<div className="row">
<div className="columns medium-6 large-4 small-centered">
{props.children}
</div>
</div>
</div>
);
}
module.exports = Main;
arctic.jsx
var React = require('react');
var ArcticForm = require('ArcticForm');
var ArcticMessage = require('ArcticMessage');
var Arctic = React.createClass({
getDefaultProps: function () {
return {
name: "polar bear!"
};
},
getInitialState: function () {
return {
name: this.props.name
};
},
handleNewData: function (updates) {
this.setState(updates);
},
render: function(){
var name = this.state.name;
return (
<div>
<h1 className="text-center">Arctic</h1>
<ArcticForm onNewData={this.handleNewData}/>
<ArcticMessage name={name}/>
</div>
)
}
});
module.exports = Arctic;
ArcticForm.jsx
var React = require('react');
var ArcticForm = React.createClass({
onFormSubmit: function (e) {
e.preventDefault();
var updates = {};
var name = this.refs.name.value;
if (name.length > 0) {
this.refs.name.value = '';
updates.name = name;
}
this.props.onNewData(updates);
},
render: function () {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input type="text" ref="name" placeholder="Name" />
<button type="submit" className="button expanded hollow">
Submit
</button>
</form>
</div>
);
}
});
module.exports = ArcticForm;
ArcticMessage.jsx
var React = require('react');
var ArcticForm = require('ArcticForm');
var ArcticMessage = React.createClass({
render: function () {
var name = this.props.name;
return (
<h3 className="text-center">Hi {name}</h3>
);
}
});
module.exports = ArcticMessage;
The package instructions tell me to include this, but where and how? And how to include that in webpack?
import React from 'react';
import ReactDOM from 'react-dom';
import { RippleButton } from 'react-ripple-effect';
class App extends React.Component {
render(){
return(
<RippleButton>Click On Me!</RippleButton>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"))
You don't import in webpack...Webpack is responsible to read your source and bundle all necessary modules.
The idea is:
You install a module using NPM.
You use inside your source code using import <module>
When bulding with webpack, it reads your source code, find that import and bundles it.
Related
I try to recreate an existing monaco+react+typescript project to my own goals. And it's not working, unfortunately. Language functionalities don't work. When I tried to throw alerts from the setupLanguage function it's working on getWorkerUrl function only. But don't work for the monaco.languages.onLanguage event processor.
May I ask you to show me the point where I'm wrong?
Regards, vladimir
P.s. Code are available on https://github.com/vladimirkozhaev/monaco-web-editor-new-edition
This is my setup.ts
import * as monaco from "monaco-editor-core";
import { languageExtensionPoint, languageID } from "./config";
import { richLanguageConfiguration, monarchLanguage } from "./TodoLang";
import { TodoLangWorker } from "./todoLangWorker";
import { WorkerManager } from "./WorkerManager";
import DiagnosticsAdapter from "./DiagnosticsAdapter";
import TodoLangFormattingProvider from "./TodoLangFormattingProvider";
export function setupLanguage() {
(window as any).MonacoEnvironment = {
getWorkerUrl: function (moduleId, label) {
if (label === languageID)
return "./todoLangWorker.js";
return './editor.worker.js';
}
}
monaco.languages.register(languageExtensionPoint);
monaco.languages.onLanguage(languageID, () => {
monaco.languages.setMonarchTokensProvider(languageID, monarchLanguage);
monaco.languages.setLanguageConfiguration(languageID, richLanguageConfiguration);
const client = new WorkerManager();
const worker: WorkerAccessor = (...uris: monaco.Uri[]): Promise<TodoLangWorker> => {
return client.getLanguageServiceWorker(...uris);
};
//Call the errors provider
new DiagnosticsAdapter(worker);
monaco.languages.registerDocumentFormattingEditProvider(languageID, new TodoLangFormattingProvider(worker));
});
}
export type WorkerAccessor = (...uris: monaco.Uri[]) => Promise<TodoLangWorker>;
This is my package.json
{
"name": "todolangeditor",
"version": "1.0.0",
"description": "TodoLang editor",
"license": "UNLICENSED",
"scripts": {
"test": "jest -c jest.config.unit.js",
"start": "webpack-dev-server",
"antlr4ts": "antlr4ts ./ExpressionsParserGrammar.g4 -visitor -o ./src/ANTLR"
},
"dependencies": {
"antlr4ts": "0.5.0-alpha.4",
"monaco-editor-core": "0.18.1",
"react": "16.8.6",
"react-dom": "16.8.6"
},
"devDependencies": {
"#types/react": "16.8.12",
"source-map-loader": "^1.0.0",
"#types/react-dom": "16.8.3",
"antlr4ts-cli": "0.5.0-alpha.4",
"css-loader": "3.3.0",
"html-webpack-plugin": "3.2.0",
"style-loader": "1.0.1",
"ts-loader": "5.3.3",
"typescript": "^4.8",
"webpack": "4.29.6",
"webpack-cli": "3.3.0",
"webpack-dev-server": "3.2.1",
"ts-jest": "^29.0.3",
"#types/jest":"29.0.3"
}
}
This is my webpack.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
const { SourceMapDevToolPlugin } = require("webpack");
module.exports = {
mode: 'development',
entry: {
app: './src/index.tsx',
"editor.worker": 'monaco-editor-core/esm/vs/editor/editor.worker.js',
"todoLangWorker": './src/todo-lang/todolang.worker.ts'
},
output: {
globalObject: 'self',
filename: (chunkData) => {
switch (chunkData.chunk.name) {
case 'editor.worker':
return 'editor.worker.js';
case 'todoLangWorker':
return "todoLangWorker.js"
default:
return 'bundle.[hash].js';
}
},
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.tsx?/,
loader: 'ts-loader'
},
{
test: /\.css/,
use: ['style-loader', 'css-loader']
},
{
test: /\.js$/,
enforce: 'pre',
use: ['source-map-loader']
}
]
},
plugins: [
// new SourceMapDevToolPlugin({
// filename: "[file].map"
// }),
new htmlWebpackPlugin({
template: './src/index.html'
})
]
}
This is my index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {setupLanguage} from "./todo-lang/setup";
import { Editor } from './components/Editor/Editor';
import { languageID } from './todo-lang/config';
import { parseAndGetSyntaxErrors, parseAndGetASTRoot } from './language-service/Parser';
setupLanguage();
const App = () => <Editor language={languageID}></Editor>;
ReactDOM.render(<App/>, document.getElementById('container'));
I am new to Vuex and I have problem. I cannot serve my app properly using npm run serve. I can open the app on localhost but it display nothing, just html body with styled background color. Previously I do npm run build
F:\Javascript\CodeHighlighter>npm run build
> code-highlighter#0.1.0 build F:\Javascript\CodeHighlighter
> vue-cli-service build
- Building for production...
DONE Compiled successfully in 6447ms 08:44:40
File Size Gzipped
dist\js\chunk-vendors.74c072d0.js 120.47 KiB 42.78 KiB
dist\js\app.f18138cd.js 5.18 KiB 2.08 KiB
dist\css\app.60b393b9.css 1.78 KiB 0.65 KiB
Images and other types of assets omitted.
DONE Build complete. The dist directory is ready to be deployed.
INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
Then I do npm run serve
F:\Javascript\CodeHighlighter>npm run serve
> code-highlighter#0.1.0 serve F:\Javascript\CodeHighlighter
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
DONE Compiled successfully in 4139ms 08:45:52
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.0.116:8080/
Note that the development build is not optimized.
To create a production build, run npm run build
when I open http://localhost:8080/ and open console. There is 1 error and 2 warning.
[Vue warn]: Property "$store" was accessed during render but is not defined on instance.
at <Header>
at <App>
[Vue warn]: Unhandled error during execution of render function
at <Header>
at <App>
Uncaught TypeError: Cannot read property 'getters' of undefined
There is my directory
And there is my full code
main.js
import { createApp } from 'vue'
import { createStore } from 'vuex'
import { store } from './store/store'
import App from './App.vue'
// console.log(store);
const app = createApp(App).mount('#app');
const vuestore = createStore(store);
app.use(vuestore);
store.js
import Vuex from 'vuex';
export const store = new Vuex.Store({
strict:true,
state:{
title: 'Code Highlighter',
copyright:{
license : 'MIT',
author : 'Philip Purwoko',
repository : 'https://github.com/PhilipPurwoko/CodeHighlighter'
},
api: "https://highlight-code-api.jefrydco.vercel.app/api",
langs: ["javascript", "python"]
},
getters:{
getTitle:state=>{
return state.title;
},
getCopyright:state=>{
return state.copyright;
},
getAPI:state=>{
return state.api;
},
getLangs:state=>{
return state.langs;
}
}
});
App.vue
<template>
<main>
<app-header></app-header>
<code-block></code-block>
<app-footer></app-footer>
</main>
</template>
<script>
import Header from "./components/Header.vue";
import Footer from "./components/Footer.vue";
import CodeBlock from "./components/CodeBlock.vue";
export default {
components: {
"app-header": Header,
"code-block": CodeBlock,
"app-footer": Footer,
},
};
</script>
CodeBlock.vue
<template>
<div>
<form>
<strong class="monospace">Select Language</strong>
<select v-model="lang" #change="highlight">
<option selected disabled>Choose Language</option>
<option v-bind:key="lan" v-for="lan in getLangs">{{ lan }}</option>
</select>
</form>
<section class="code-container">
<textarea class="code-block" v-model="code" #input="highlight" ></textarea>
<div class="code-block formated" v-html="formated"></div>
</section>
</div>
</template>
<script>
import axios from "axios";
import { mapGetters } from 'vuex';
export default {
data: function() {
return {
lang: "",
code: "",
formated: ""
};
},
computed:{
...mapGetters([
'getAPI',
'getLangs',
'getFormated',
'getCode'
])
},
methods: {
highlight() {
if (this.code == "") {
this.code = " ";
}
if (this.lang != "") {
axios
.post(
this.getAPI + `?lang=${this.lang}`,
{
code: this.code
}
)
.then(res => {
this.formated = res.data.data;
});
} else {
this.formated = "<p class='monospace' style='color:azure;'>No language selected. Please select a language</p>";
}
}
}
};
</script>
package.json
{
"name": "code-highlighter",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.20.0",
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vuex": "^4.0.0-beta.4"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0-0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
You can also access my github repository at here (https://github.com/PhilipPurwoko/CodeHighlighter/tree/restart). I really appreciate for all of your responses. Thank you
First, please read the Vuex documentation for Vue 3. I've found the mistake you've made that you should use the Vue plugin before mounting the Vue Instance. It's should look like this. Good luck!
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
// Create vue instance
const app = createApp(App);
// Install the plugin first
app.use(store);
// Mount your app
app.mount('#app');
I deployed a Node application to CouchDB that I developed and built from a Vue Webpack template. One of the modules I rely on, pdfjs-dist, relies on a worker.
After running npm run build and getting my output in dist, I copy the output files to couchapp to deploy them to CouchDB. I get no errors during deployment and the site looks fine once it's up.
However, when I try doing something that requries pdfjs-dist, I get the error:
NetworkError: Failed to load worker script at
"http://.../docuapp/documentation/_design/uploads/static/js/app.4eb1aecbadc78360a76e.worker.js"
(unbekannt)
Error: Loading chunk 0 failed.
Stack-Trace:
u#http://.../docuapp/documentation/_design/uploads/static/js/manifest.a6f78538bddeebdefd4a.js:1:957
manifest.a6f78538bddeebdefd4a.js:1:1378
Error: Loading chunk 0 failed. manifest.a6f78538bddeebdefd4a.js:1:957
So I check out the url that's failing to load, and the document is missing. But when I remove the worker part of the url, i.e.
http://.../docuapp/documentation/_design/uploads/static/js/app.4eb1aecbadc78360a76e.js
This page loads, and I'm guessing that's the resource that's needed.
Does anyone have any guesses as to what's going wrong here?
Here's my package.json
{
"name": "docu-back",
"version": "1.0.0",
"description": "A Vue.js project",
"author": "",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"build": "node build/build.js"
},
"dependencies": {
"element-ui": "^2.0.11",
"mime-types": "^2.1.17",
"nano": "^6.4.2",
"node-dir": "^0.1.17",
"pdfjs-dist": "^2.0.332",
"querystring-browser": "^1.0.4",
"vue": "^2.5.2",
"vue-awesome": "^2.3.4",
"vue-router": "^3.0.1"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"chalk": "^2.0.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.11.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
build/build.js
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
build/webpack.base.conf.js
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
querystring: 'querystring-browser',
'#': resolve('src'),
'_qs': 'querystring-browser'
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
build/webpack.dev.conf.js
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
build/webpack.prod.conf.js
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
I'll gladly provide any other files if they're helpful.
Here's how I import pdfjs-dist:
text.js
var pdfjs = require('pdfjs-dist');
pdfjs.disableWorker = true
My guess on the problem is that pdfjs requires the workerSrc property to be known in runtime. But when you use webpack it will probably assign an unguessable hash on the file name, so you can't really put the filename as a string in your code.
But pdfjs provides a solution for us! They have included a webpack file in their distribution.
In your code
var pdfjs = require("pdfjs-dist/webpack");
//we dont't include the normal module
//but the one with the webpack configuration
//that the pdfjs team provides us.
//no need to disable worker
//or point to the workerSrc
So what this thing does
//inside "pdfjs-dist/webpack"
'use strict';
var pdfjs = require('./build/pdf.js');
var PdfjsWorker = require('worker-loader!./build/pdf.worker.js');
if (typeof window !== 'undefined' && 'Worker' in window) {
pdfjs.GlobalWorkerOptions.workerPort = new PdfjsWorker();
}
module.exports = pdfjs;
Basically it includes the original build from ./build/pdf.js and it will also import for us the worker script with the worker-loader. A webpack loader designed to import web-workers in our apps. Then it assigns the actual worker in the pdfjs instance and it exports it.
After you import the above file in your app you will have a pdfjs instance configured with a web-worker ready for your bundle!
Maybe I am just not using axios correctly but I currently have a react front-end and node.js back end.
I am trying to POST to my api endpoint "/api/:id/addItem" but nothing is logging when making the request.
Here is my code:
ListForm component ->
import React from 'react';
import * as helpers from '../helpers';
class ListForm extends React.Component {
state = {
value: ''
}
handSubmit = e => {
e.preventDefault();
helpers.addItem(this.props.currentUser.googleId, this.state.value);
this.setState({value: ''});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
value={this.state.value}
onChange={e => this.setState({value: e.target.value})}
/>
<button>Add item</button>
</form>
);
}
}
export default ListForm;
Routes ->
const mongoose = require('mongoose');
const User = require('../models/userSchema');
module.exports = (app) => {
app.post('/api/:id/addItem', (req, res) => {
console.log('HEY!');
});
};
helpers.js ->
import axios from 'axios';
export const fetchUser = async () => {
const resp = await axios.get('/api/current_user');
return resp.data;
}
export const addItem = async (id, newItem) => {
const resp = await axios.post("/api/" + id + "/addItem", newItem);
return resp.data;
}
Package.json to show forwarding requests->
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
},
"/api/*": {
"target": "http://localhost:5000"
}
},
"dependencies": {
"axios": "^0.17.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.0.17"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Issue here is with newItem , its not json it's just simple value
axios.post("/api/" + id + "/addItem", newItem);
It should be like :
axios.post("/api/" + id + "/addItem", {value : newItem});
Or pass json from addItem :
helpers.addItem(this.props.currentUser.googleId, this_should_be_json );
I want to store the username and password entered by the user into mysql database using node.js. The front end is in React.js.
The following code I have:
Login.html:
<head>
<meta charset = "UTF-8">
<title>Login</title>
</head>
<body>
<div id = "root"></div>
<script src = "BundleLogin.js"></div>
</script>
</body>
</html>
LoginClass.js
import React from 'react';
import mysql from 'mysql';
require('./stylecs.css');
//ar express = require("express");
//var mysql = require('mysql');
class LoginClass extends React.Component {
constructor(props) {
super(props);
this.state =
{
text:
{
username:'',
password:'',
},
valid:true,
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleReset = this.handleReset.bind(this);
}
handleChange(property, event) {
console.log(event.target.value);
const text = this.state.text;
text[property] = event.target.value;
this.setState({text: text});
}
handleSubmit(event) {
if(("Malathi".localeCompare(this.state.text.username) == 0) && ("Tryanuka".localeCompare(this.state.text.password)==0) )
alert('You are a valid user.\n Sign in details: \nUser Name:' + this.state.text.username
+'\nPassword :' + this.state.text.password );
else
alert('Username or Password are incorrect.');
}
handleFocus()
{
this.setState({valid:false});
}
validateEmail(event)
{
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (this.state.valid && !filter.test(this.state.text.username))
{
return (
<div>
<label className="error">Please enter valid email.</label>
</div>
);
}
}
handleReset(event)
{
this.setState(
{
text:
{
username:'',
password:'',
}
});
}
render() {
return (
<div className = "mainbox"><br/>
<div className="heading"> Login Page</div>
<div className="calign">
<input className="tbox" type="text" placeholder="Name"
value={this.state.text.username}
onFocus= {this.handleFocus}
onChange={this.handleChange.bind(this, 'username')} />
{this.validateEmail(this.state.text.username)}
</div>
<br/>
<div className="calign">
<input className="tbox" type="password" placeholder="Password"
value={this.state.text.password}
onChange={this.handleChange.bind(this, 'password')}/>
<br/><br/>
</div>
<div className="calign">
<button className ="btn" onClick={this.handleSubmit}>Sign in</button>
<button className ="btn" onClick={this.handleReset}>Reset</button><br/>
Forgot?
</div>
</div>
);
}
}
export default LoginClass;
Package.json
{
"name": "hrportal",
"version": "1.0.0",
"description": "",
"main": "Login.js",
"scripts": {
"start": " webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.7",
"babel-preset-latest": "^6.16.0",
"babel-preset-react": "^6.16.0",
"css-loader": "^0.25.0",
"express": "^4.14.0",
"mysql": "^2.12.0",
"node-mysql": "^0.4.2",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-input-link": "0.0.5",
"react-popup": "^0.4.2",
"react-router": "^3.0.0",
"react-validation": "^2.10.9",
"style-loader": "^0.13.1",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
webpack.config.in
var config = {
entry: './LoginMain.js',
output: {
path:'./',
filename: 'BundleLogin.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['latest', 'react','es2015']
}
},
{
test: /\.css?$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader',
},
]
},
externals: {
'react': 'React'
},
target: 'node',
}
module.exports = config;
I want to store the data from react to mysql using node.js. I appreciate your help.