monaco web editor, language functionality don't working - antlr4

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'));

Related

in my production file: Uncaught SyntaxError: Unexpected token 'export' vitejs

in vite.config.js
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
build: {
target: 'es2015',
manifest: true,
minify: true,
reportCompressedSize: true,
lib: {
entry: path.resolve(__dirname, "main.js"),
fileName: "main",
formats: ["es", "cjs"],
},
rollupOptions: {
external: [],
output: {
dir: 'dist'
}
},
},
})
in file main.js
import functions from './functions'
export { functions }
in file functions.js
const isPrime = (n) => {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
export default isPrime
in file package.json
{
"name": "vite-project",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"path": "^0.12.7",
"vite": "^4.1.0"
}
}
The idea is that this package can be used:
in the browser
main.isPrime(50)
or
import Main from 'main';
the error appears only in the production file /dist/main.js when I use it in the browser:
Uncaught SyntaxError: Unexpected token 'export'
Thank you for reading
I have changed this line in main.js file
// export { functions }
to
window.functions = functions
but when i wanted to do this it didn't work
import Main from 'main';

Webpack build gives javascript memory heap error

I have my Webpack configuration as follows for a NodeJS project with TypeScript. When it is compiling it gives the "JavaScript memory Heap" error in the terminal. I usually increase the memory limit in the local terminal in order to do have the output build folder. But this is not the case with the server as it has some memory limitations. Can someone help me to sort out this issue either with the parallel build or any memory optimization technics.
This is my package.json.
"devDependencies": {
"fs": "^0.0.1-security",
"glob": "^8.0.3",
"path": "^0.12.7",
"ts-loader": "^9.4.1",
"ts-node": "^10.9.1",
"typescript": "^4.9.3",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.0",
"zip-webpack-plugin": "^4.0.1"
},
"dependencies": {
"#types/aws-lambda": "^8.10.109",
"#types/tedious": "^4.0.9",
"aws-sdk": "^2.1257.0",
"axios": "^1.2.0",
"jsonwebtoken": "^8.5.1",
"node-tls": "^0.10.2",
"sequelize": "^6.28.0",
"tedious": "^15.1.2"
}
as per the above dependencies I use Webpack 5.
This is the Webpack.config.js
const webpack = require('webpack');
const path = require("path");
const glob = require("glob");
const ZipPlugin = require("zip-webpack-plugin");
const tedious = require("tedious");
const TerserPlugin = require('terser-webpack-plugin');
const entries = () => {
const src = path.resolve(__dirname, "functions");
const files = glob.sync(src + "/**/*");
return files
.filter((f) => f.indexOf("index.ts") > -1)
.map((f) => "./" + path.relative(path.resolve(__dirname), f));
};
const getBundleName = (path) =>
path
.substring("./functions/".length, path.lastIndexOf("/"))
.replaceAll("/", "-")
.toLowerCase();
const config = () => {
let modules = [];
const files = entries();
files.forEach((f) => {
console.log(f)
const bundleName = getBundleName(f);
const outputPath = path.resolve(
__dirname,
"dist/" +
bundleName.substring(0, bundleName.lastIndexOf("-")) +
"/" +
bundleName.substring(bundleName.lastIndexOf("-") + 1)
);
const moduleConfig = {
name: bundleName,
entry: f,
output: {
path: outputPath,
filename: "index.js",
libraryTarget: "commonjs",
clean: true,
},
module: {
rules: [
{
test: /\.ts?$/,
use: "ts-loader",
exclude: [/node_modules/, /\.test.ts?$/],
},
],
},
target: "node",
plugins: [
new ZipPlugin({
path: "./",
filename: `${bundleName}.zip`,
}),
new webpack.ids.DeterministicChunkIdsPlugin({
maxLength: 5,
}),
],
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
}),
],
chunkIds: 'named',
concatenateModules: true,
emitOnErrors: true,
mangleWasmImports: true,
moduleIds: 'deterministic',
runtimeChunk: {
name: 'runtime',
},
sideEffects: 'flag',
usedExports: 'global',
},
resolve: {
mainFields: ["main"],
extensions: [".tsx", ".ts", ".js", ".json", "..."],
alias: {'tedious': path.join(__dirname, './node_modules/tedious')},
},
resolveLoader: {
modules: ["node_modules"],
},
externals: ['pg', 'sqlite3', 'tedious', 'pg-hstore'],
/*devtool: "source-map",*/
};
modules.push(moduleConfig);
});
return modules;
};
module.exports = config();
I am expecting to understand the issues or any improvements of my Webpack configuration for the memory optimization for the code build with this nodejs TS project.

How to use imports in content script with Vite without external library like https://crxjs.dev/vite-plugin?

There's an issue with importing es modules into the content script:
(How to import ES6 modules in content script for Chrome Extension)
Maybe there is a way to build the content script in one file to resolve this?
I'm using this boilerplate - https://github.com/JohnBra/vite-web-extension. Here's what my vite config looks like:
import react from "#vitejs/plugin-react-swc";
import { resolve } from "path";
import { defineConfig } from "vite";
import copyContentStyle from "./utils/plugins/copy-content-style";
import makeManifest from "./utils/plugins/make-manifest";
const root = resolve(__dirname, "src");
const pagesDir = resolve(root, "pages");
const assetsDir = resolve(root, "assets");
const outDir = resolve(__dirname, "dist");
const publicDir = resolve(__dirname, "public");
const IS_DEV = process.env.DEV === "true";
export default defineConfig({
resolve: {
alias: {
"#src": root,
"#assets": assetsDir,
"#pages": pagesDir,
},
},
plugins: [react(), makeManifest(), copyContentStyle()],
publicDir,
build: {
minify: !IS_DEV,
outDir,
sourcemap: IS_DEV,
emptyOutDir: IS_DEV,
rollupOptions: {
input: {
// devtools: resolve(pagesDir, 'devtools', 'index.html'),
// panel: resolve(pagesDir, "panel", "index.html"),
content: resolve(pagesDir, "content", "index.ts"),
background: resolve(pagesDir, "background", "index.ts"),
popup: resolve(pagesDir, "popup", "index.html"),
// newtab: resolve(pagesDir, "newtab", "index.html"),
// options: resolve(pagesDir, "options", "index.html"),
},
output: {
entryFileNames: (chunk) => {
return `src/pages/${chunk.name}/index.js`;
},
},
},
},
});
I tried having a separate vite config for the content scripts to build it in one file. But, I was not successful
Here's what the config for that looks like:
import { resolve } from "path";
import { defineConfig } from "vite";
import copyContentStyle from "./utils/plugins/copy-content-style";
import { viteSingleFile } from "vite-plugin-singlefile";
const root = resolve(__dirname, "src");
const pagesDir = resolve(root, "pages");
const assetsDir = resolve(root, "assets");
const outDir = resolve(__dirname, "dist");
const publicDir = resolve(__dirname, "public");
const IS_DEV = process.env.DEV === "true";
export default defineConfig({
resolve: {
alias: {
"#src": root,
"#assets": assetsDir,
"#pages": pagesDir,
},
},
plugins: [copyContentStyle(), viteSingleFile()],
publicDir,
build: {
minify: !IS_DEV,
outDir,
sourcemap: IS_DEV,
emptyOutDir: IS_DEV,
rollupOptions: {
input: {
content: resolve(pagesDir, "content", "index.ts"),
},
output: {
dir: `src/pages/content`,
},
},
},
});
I ended up having a separate vite config for the content script, which looks like:
import { resolve } from "path";
import { defineConfig } from "vite";
import { viteSingleFile } from "vite-plugin-singlefile";
const root = resolve(__dirname, "src");
const pagesDir = resolve(root, "pages");
const outDir = resolve(__dirname, "dist", "src", "pages", "content");
const IS_DEV = process.env.DEV === "true";
export default defineConfig({
resolve: {
alias: {
"#src": root,
"#pages": pagesDir,
},
},
plugins: [viteSingleFile()],
build: {
copyPublicDir: false,
minify: !IS_DEV,
outDir,
sourcemap: IS_DEV,
emptyOutDir: IS_DEV,
rollupOptions: {
input: {
content: resolve(pagesDir, "content", "index.ts"),
},
output: {
entryFileNames: "index.js",
},
},
},
});
And, I run it all with:
"scripts": {
"build:general": "vite build",
"build:content": "vite build --config vite.contentScript-config.ts",
"build": "run-p build:*",
"dev:general": "vite build --watch --mode development",
"dev:content": "vite build --config vite.contentScript-config.ts --watch --mode development",
"dev": "run-p dev:*"
},

Worker Script Failing to Load for Vue Webpack Built 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!

React Webpack add new npm package

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.

Resources