I decided to use esbuild to bundle my express API. So far all is good, except that the public directory which holds the swagger UI is not being bundled with the rest of the application.
I have an endpoint defined as a static route which serves that folder.
app.use(express.static(`${root}/public`));
To overcome this problem I have tried multiple things, such as manually copying the public directory to the build dir location. That did not seem to work.
I have also tried with the plugin esbuild-plugin-public-directory, which did not work either.
Then I added the public/index.html to the entryPoints configuration, which did not work either.
My question now is, what am I doing wrong? I don't seem to find anything particularly useful over the internet to help me overcome this problem.
This is the esbuild config which I am currently using.
const publicDir = require("esbuild-plugin-public-directory");
const OUTDIR = "build";
const envPlugin = {
name: "env",
setup(build) {
// Intercept import paths called "env" so esbuild doesn't attempt
// to map them to a file system location. Tag them with the "env-ns"
// namespace to reserve them for this plugin.
build.onResolve({ filter: /^env$/ }, (args) => ({
path: args.path,
namespace: "env-ns",
}));
// Load paths tagged with the "env-ns" namespace and behave as if
// they point to a JSON file containing the environment variables.
build.onLoad({ filter: /.*/, namespace: "env-ns" }, () => ({
contents: JSON.stringify(process.env),
loader: "json",
}));
},
};
require("esbuild")
.build({
entryPoints: ["server/start.ts", "public/index.html"],
platform: "node",
bundle: true,
minify: false,
platform: "node",
logLevel: "info",
sourcemap: false,
target: "node12",
loader: {
'.html': 'text',
},
outdir: "build",
plugins: [envPlugin, publicDir()],
})
.then(() => {
fs.copyFileSync("server/common/api.yml", `${OUTDIR}/api.yml`);
console.log(`Successfully built, output directed to the ${OUTDIR} directory`);
})
.catch(() => process.exit(1));
I tried it out if using #fastify/swagger. Just put #fastify/swagger in esbuild build.external
buid({external: ["esnext", "#fastify/swagger"],})
Otherwise maybe put swagger-ui-dist. Reference: https://docs.devland.is/repository/openapi#configuring-swaggerui-dependencies-for-esbuild
Related
I have a static page that doesn't need JavaScript. I'm using vue-cli 3 and would like to pass the HTML file through webpack for the purpose of minification. However, this doesn't seem to be possible. Inside vue.config.js, I have this:
module.exports = {
pages: {
static_page: {
template: "./public/static_page.html",
entry: ""
}
}
};
Of course, this fails because entry is required and cannot be empty. Simply placing the file into public will cause vue-cli to copy the file into dist unchanged. This is OK but it's not minified. So how can I tell vue-cli to process a HTML file without JavaScript?
I had to manually invoke the HTML Webpack Plugin. Here's my vue.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
configureWebpack: {
plugins: [
new HtmlWebpackPlugin({
template: "./public/static_page.html",
filename: "static_page.html",
chunks: [],
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
}
})
]
}
};
Vue CLI is still copying the file from public to dist unchanged as it would with any other static asset. HTML Webpack Plugin is overwriting this file with the minified version.
Also, setting the minify option to true doesn't seem to do anything. The options have to be listed out explicitly. See Issue #1094.
Another useful link is the list of HTML Webpack Plugin options.
I am trying to use esbuild to bundle and minify my files in an npm project. It is minimizing every file that I pass in, but it is not bundling. It gives me the error that I must use 'outdir' when there are multiple files. However, this gives me back all of those files, minimized, in a folder. This is not the behavior that I want and is not bundling. I just want it to take all of those files and merge them into one.
let {build} = require("esbuild");
let files = ["file1.js", "file2.js"];
build({
entryPoints: files,
outdir: "./views/dashboardPage/bundle",
minify: true,
bundle: true
}).catch(() => process.exit(1));
I have bundle set to true, but it still demands that I use outdir and it just returns those files to me, minimized. They have basically 0 documentation on this and every post online about it has just copy/pasted the README from the GitHub. How can I make it bundle?
Each entry point file will become a separate bundle. Each bundle includes the entry point file and all files it imports. Passing two entry points will create two separate bundles. The bundling process is not the same thing as file concatenation.
If you want all of the files in a single bundle, you can reference them all from a single file and use that file as the entry point:
import "./file1.js"
import "./file2.js"
Doing that with esbuild could look something like this:
let {build} = require("esbuild");
let files = ["./file1.js", "./file2.js"];
build({
stdin: { contents: files.map(f => `import "${f}"`).join('\n') },
outfile: "./views/dashboardPage/bundle.js",
minify: true,
bundle: true
}).catch(() => process.exit(1));
You can use inject option (https://esbuild.github.io/api/#inject), for example,
const options = {
entryPoints: ['index.js'],
inject: ['file1.js', ..., 'fileN.js'],
bundle: true,
minify: true,
sourcemap: true,
outdir: path,
};
esbuild.buildSync(options);
Based on Alexander response I finally came to this solution to pack a whole folder into a single file:
const esbuild = require('esbuild');
const glob = require('glob');
esbuild
.build({
stdin: { contents: '' },
inject: glob.sync('src/js/**/*.js'),
bundle: true,
sourcemap: true,
minify: true,
outfile: 'web/js/bundle.js',
})
.then(() => console.log("⚡ Javascript build complete! ⚡"))
.catch(() => process.exit(1))
The problem is because the files are not being found.
Install this package to grab all files from the folder:
npm i files-folder
Your esbuild.config.js file will look like this one:
import { filesFromFolder } from 'files-folder'
import esbuild from 'esbuild'
esbuild
.build({
entryPoints: filesFromFolder('src'),
bundle: true,
minify: true,
sourcemap: true,
target: 'node16',
define: { 'require.resolve': undefined },
platform: 'node',
allowOverwrite: true,
outdir: 'views/dashboardPage/bundle'
})
.catch((error) => {
process.exit(1)
})
For my firebase application I need some backend functions that would load i18n files and send them to client. I am able to use webpack to bundle the files for deploying. That works fine. But what I would also like to do is to change the content of the files (because phrases in the app may be added or deleted), which is not possible in this case. Is there a way to upload these files along with the scripts?
There is this section in the firebase documentation: https://firebase.google.com/docs/functions/handle-dependencies. However, I wouldn't really like to write "language_namespace": "file:locales/language/namespace.json" for each file I have.
I didn't find any easy workaround and I will probably use some other system for the i18n, because this one is overcomplicated and it will not be easy to work with. Anyway, here is the solution in case someone faces a similar problem:
I used webpack-cli instead of tsc to bundle my files. Here is what my folder structure looked like:
root
- functions
- webpack.config.js
- lib
- src
- index.ts // File with the function
- ...
- public
- locales // Locales folder I needed to be uploaded
- en
- ...
- ru
- ...
- ...
- ...
- ...
It seems like firebase will upload anything that it finds in the lib folder, so when bundling the functions, I just used copy-webpack-plugin to copy locales there. Here is what my webpack config looked like:
const path = require('path')
const nodeExternals = require('webpack-node-externals')
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'lib'),
libraryTarget: 'this',
filename: 'index.js',
},
mode: 'development',
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
target: 'node',
externals: [nodeExternals()],
module: {
rules: [
{ test: /\.tsx?/, loader: 'ts-loader', options: { transpileOnly: true } },
]
},
plugins: [
new CopyWebpackPlugin([{
from: path.resolve(__dirname, '../public/locales'),
to: './locales'
}])
]
}
Then, to prevent webpack from changing normal require to __webpack_require__whatever, I had to use the __non_webpack_require__ function, that would then be transpiled to normal require and let me read copied files from lib/locales:
// In case you are using typescript and want to prevent the compiler
// from arguing that `__non_webpack_require__` is not defined
declare function __non_webpack_require__(module: string): any
export const getLocale = functions.https.onRequest((req, res) => {
const { language, namespace } = req.query
try {
const translation = __non_webpack_require__(`./locales/${language}/${namespace}.json`)
// do stuff
res.send(translation)
} catch(e) {
if(e.code === 'MODULE_NOT_FOUND') {
res.status(400).end("Couldn't find translation for ${language}/${namespace}")
} else { /* ... */ }
}
})
After doing this, both firebase emulators:start --only functions and firebase deploy --only functions:getLocale worked correctly
Ive been using the XTK library for some scientific 3D modeling applications, and I am trying to use it in react. The library works flawlessly on its own in JavaScript but when I try to implement it in react it tells me that I need a loader for an unspecified file type. How would I figure out what the file type is? and why is this issue happening.
package docs: https://www.npmjs.com/package/xtk
here is the implementation of xtk in code:
var r = new window.X.renderer3D();
//r.container = 'r';
r.init();
// create a mesh from a .vtk file
var skull = new window.X.mesh();
skull.file = 'http://x.babymri.org/?avf.vtk';
// add the object
r.window.X.add(skull);
// .. and render it
r.render();
And here is the error message I am getting:
Ill go a ahead and add the webpack config as well at the recommendation of Nicholas Tower:
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
var vtkRules = require('vtk.js/Utilities/config/dependency.js').webpack.v2.rules;
var entry = path.join(__dirname, './src/index.js');
const sourcePath = path.join(__dirname, './src');
const outputPath = path.join(__dirname, './dist');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
{ test: entry, loader: "expose-loader?MyWebApp" },
{ test: /\.html$/, loader: 'html-loader' },
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
]
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
].concat(vtkRules),
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};
I have a create-react-app nodejs app using:
npx create-react-app client
Added the Cesium library
cd client
npm install --save cesium
ejected the app:
npm run eject
and modified webpack config by following the instructions described in Cesium and Webpack
And I am getting the following error:
./src/index.js
Module not found: Can't resolve 'cesium/Cesium' in '/home/client/src'
the import statement in index.js is:
import Cesium from 'cesium/Cesium';
Any pointers to what I should do?
I commented out the ModuleScopePlugin statement in the plugins section.
As suggested in the cesium page, I added an alias like so:
const cesiumSource = 'node_modules/cesium/Source';
...
'cesium': path.resolve(__dirname, cesiumSource)
but apparently it is trying to import it from src.
I have pasted the whole webpack.config.prod.js file here:
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const CopywebpackPlugin = require('copy-webpack-plugin');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// The path to the Cesium source code
const cesiumSource = 'node_modules/cesium/Source';
const cesiumWorkers = '../Build/Cesium/Workers';
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
// Needed to compile multiline strings in Cesium
sourcePrefix: ''
},
amd: {
// Enable webpack-friendly use of require in Cesium
toUrlUndefined: true
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Cesium module name
cesium: path.join(__dirname, cesiumSource)
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
//new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/, /\.xml$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
plugins: [
// Copy Cesium Assets, Widgets, and Workers to a static directory
new CopywebpackPlugin([ { from: path.join(cesiumSource, cesiumWorkers), to: 'Workers' } ]),
new CopywebpackPlugin([ { from: path.join(cesiumSource, 'Assets'), to: 'Assets' } ]),
new CopywebpackPlugin([ { from: path.join(cesiumSource, 'Widgets'), to: 'Widgets' } ]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};
Can you confirm you are using it with ES6?
If no, then first install ES6 because this statement import statement works with ES6.
import Cesium from 'cesium/Cesium';
If you are running it normally just after installing React then use this to import.
var Cesium = require('cesium/Cesium');
Use this link to setup app with ES6
- ECMAScript 6 application using Babel and Webpack