I am serving the app through Express, which needs to use ES modules. Node does allow that, but I had to replace __dirname with another solution:
server.mjs:
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
This resulted in error with Babel, which required me to add extra plugin (https://babeljs.io/docs/en/next/babel-plugin-syntax-import-meta.html). I replaced original CRA with custom webpack and created .babelrc:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-syntax-import-meta"]
}
webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js", // entry point to the application = top react component,
output: {
path: path.resolve(__dirname, "build"), // path where the transformed index.js will be stored
filename: "index_bundle.js", //name of the transformed file
},
module: {
rules: [
{
test: /\.(js|mjs|jsx)$/, use: {
loader: 'babel-loader',
}
}, // what files will be loaded by what procedure
{test: /\.css$/, use: ['style-loader', 'css-loader']},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
]
},
mode: "development",
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html" // will take the template file and transform it to include the rest
}),
]
};
I am still runing into an error when trying to build the app. It seems that all other files are built successfully, but server.mjs is still returning an error:
ERROR in ./src/server/server.mjs 9:66
Module parse failed: Unexpected token (9:66)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| import getInitialPlayerStates from "../components/functions/initialStateFunctions.mjs";
|
> var __dirname = path.resolve(path.dirname(decodeURI(new URL(import.meta.url).pathname)));
|
| var port = process.env.PORT || 4001;
# ./src/App.js 49:0-48 119:14-27
# ./src/index.js
Other .mjs files are being build alright unless I include the line with import.meta in their code - than they fail too.
What is wrong? How can I overcome this problem?
"es-dirname" library solves the problem without using "import.meta".
https://www.npmjs.com/package/es-dirname
Related
I using Webpack with Babel to compile ES6 assets in my Nodejs application, but I am getting the following error message:
You may need an appropriate loader to handle this file type.
|
| const addMrnObj = {
| ...jsonObj,
| optionalMrn: optionalMrn
| };
# ./config/eventSource/eventSourceCall.js 5:18-40
# ./src/app.js
# multi ./src/app.js
I am using Webpack of version 2.2.1 and babel-preset-es2015 of version 6.22.0
Below is my babel.rc configuration
{
"presets": [
"es2015"
],
"plugins": [
"transform-flow-strip-types",
"transform-object-rest-spread",
"transform-class-properties",
"syntax-class-properties"
]
}
And this is my Webpack configuration
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var BabiliPlugin = require('babili-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var BUILD_DIR = path.resolve(__dirname, 'dist');
var APP_DIR = path.resolve(__dirname, 'src');
var config = {
entry: [
APP_DIR + '/app.js',
],
target: 'node',
output: {
path: BUILD_DIR,
filename: 'backend.js'
},
plugins: [
new BabiliPlugin(),
new CopyWebpackPlugin([{
from: './config',
to: 'config'
}])
],
module: {
loaders: [
{
test: /\.js?/,
exclude: /node_modules/,
include: [ APP_DIR ],
loader: 'babel-loader'
}
]
}
};
module.exports = config;
Can someone point out what additional changes I need to make to resolve this error.
Try adding "#babel/preset-env" in babel.rc file under presets(also install presets).
and also your syntax is wrong this should be
{
"presets": ["#babel/preset-es2015"]
}
and file name should be .babelrc not babel.rc
I am trying to make a library of Gatsby components (using specific Gatsby library rather than general React components).
I have been compiling using just babel but I want to be able to translate any CSS-in-JS and do other things so I am trying to build using Webpack.
When I try to compile the Gatsby component it fails in the Gatsby module. I know Gatsby is untranspiled ES6 so I included node_modules in my webpack configuration to transpile but I still:
ERROR in ./node_modules/gatsby/cache-dir/gatsby-browser-entry.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/kylecalica/Code/gatsby-learn/gatsby-components/node_modules/gatsby/cache-dir/gatsby-browser-entry.js: Unexpected token (25:4)
23 |
24 | return (
> 25 | <React.Fragment>
| ^
26 | {finalData && render(finalData)}
27 | {!finalData && <div>Loading (StaticQuery)</div>}
28 | </React.Fragment>
Webpack:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebpackPlugin({
filename: "index.html"
});
module.exports = {
entry: path.join(__dirname, "/src/index.js"),
output: {
filename: 'main.js',
path: path.resolve(__dirname, "/webpack/dist")
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
]
},
plugins: [htmlWebpackPlugin],
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 9000,
open: true
}
};
I am currently trying to take what Gatsby says to do to Storybook in my code but it's hard to figure out how to translate this from their strange way into mine?
Storybook's way of webpack:
module.exports = ({ config }) => {
// Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/]
// use installed babel-loader which is v8.0-beta (which is meant to work with #babel/core#7)
config.module.rules[0].use[0].loader = require.resolve("babel-loader")
// use #babel/preset-react for JSX and env (instead of staged presets)
config.module.rules[0].use[0].options.presets = [
require.resolve("#babel/preset-react"),
require.resolve("#babel/preset-env"),
]
config.module.rules[0].use[0].options.plugins = [
// use #babel/plugin-proposal-class-properties for class arrow functions
require.resolve("#babel/plugin-proposal-class-properties"),
// use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
require.resolve("babel-plugin-remove-graphql-queries"),
]
// Prefer Gatsby ES6 entrypoint (module) over commonjs (main) entrypoint
config.resolve.mainFields = ["browser", "module", "main"]
return config
}
.babelrc :
{
"presets": [
"babel-preset-gatsby-package",
"#babel/preset-react",
"#babel/preset-env"
]
}
I solved this by converting what Storybook's webpack module had. I am still putting it through testing however but it compiles fine for now:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebpackPlugin({
filename: "index.html"
});
module.exports = {
entry: path.join(__dirname, "/src/index.js"),
output: {
filename: 'index.js',
path: path.resolve(__dirname, "webpack")
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: "babel-loader",
options: {
presets: ["babel-preset-gatsby-package"],
plugins: ["#babel/plugin-proposal-class-properties"]
},
},
exclude: [/node_modules\/(?!(gatsby)\/)/],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
]
},
plugins: [htmlWebpackPlugin],
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 9000,
open: true
}
};
(webpack.config.js file content below)
I'm trying to make a webpack exclusion on node modules.
I found that using webpack-node-externals works for it but using that on my common config causes this other error:
Require is not defined on reflect-metadata - __webpack_require__ issue
So... I was wondering how can i exclude webpack bundling also on the browser side without getting any issue.
My webpack version: 3.11.0
webpack-config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
//externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: { modules: false },
context: __dirname,
resolve: { extensions: [ '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '#ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: [ 'to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder,
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
GOT IT!
Before posting my solution, I'd like to thanks Aluan Haddad for his useful comment in my question above.
As suggested by Aluan, in fact, the problem was related to the need to use also a module loader, more than a module bundler.
So, the steps that I followed are these:
Installing requireJS ==> http://requirejs.org/docs/node.html
Removing externals: [nodeExternals()], // in order to ignore all modules in node_modules folder from my common webpack configuration and adding it under my server configuration (done before my question, but it's a really important step) [see webpack.config.js content in the question]
Adding target: 'node', before my externals point above, under my server side section (done before my question, but it's a really important step) [see webpack.config.js content in the question]
This makes sure that browser side keeps target:'web' (default target), and target becomes node just for the server.
launched webpack config vendor command manually from powershell webpack --config webpack.config.vendor.js
launched webpack config command manually from powershell webpack --config webpack.config.js
That worked for me! Hope It will works also for anyone else reading this question and encountering this issue!
So i am trying to figure out how to use webpack to replace our current brunch build process. Basically we have an angular 1 app which doesnt utilise requires or imports at all and I want to have webpack just concat+transpile the files (there are both coffee and sass files and ill need to be able to watch and create source maps using the usual settings). This angular app is sitting inside another application which is using webpack extensively.
What is the simplest way to accomplish this? Is this even possible without the app using any form of javascript modules?
Here is my current config:
var webpack = require( "webpack" );
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require("path");
var glob = require("glob");
const exportConfig = {
entry: {
app: glob.sync('./front-end/applications/core/app/**/*.coffee'),
vendor: ['angular']
},
output: {
filename: "app.bundle.js",
path: path.join( __dirname, "../www_root/build" ),
},
debug: true,
module: {
loaders: [
{
test: /\.coffee$/,
loader: "coffee-loader"
},
{
test: /\.sass$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.(jsx|es6)/,
exclude: /(node_modules|www_root\/bower)/,
loader: "babel",
},
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js"),
new ExtractTextPlugin("[name].css", {
allChunks: true
}),
]
}
module.exports = exportConfig
I basically just get an output file with an error for each of the files obviously:
(function webpackMissingModule() { throw new Error("Cannot find module \"./front-end/applications/core/app/components/app/module.coffee\""); }());
Thanks!
I'm trying to dynamically include a .js file at webpack compile time.
I don't want to use a context to load environmental variables, because I don't these magic variables in my code.
What I'm trying to do is use the val loader to execute a module. There use an environment variable to decide what module to import. And export that module.
However, this is causing other loaders to throw errors.
Here's my dir layout
--base
--src
app.js
test.js
webpack.config.js
rawr.js
Here my webpack.config.js file
var path = require('path');
var webpack = require('webpack');
// var process = require('process');
var env = require(process.env.NODE_ENV || './devConf.js');
module.exports = {
// Specify logical root of the sourcecode
plugins: [
new webpack.DefinePlugin(env)
],
context: path.join(__dirname, '/src'),
entry: {
app: ['bootstrap.js'],
},
// Specify where to put the results
output: {
path: path.join(__dirname, '/dist'),
filename: 'build.js'
},
// Specify logical root of package imports so as to avoid relative path everywhere
resolve: {
root: path.join(__dirname, '/src'),
// What files we want to be able to import
extensions: ['', '.js', '.css', '.less'],
},
module: {
preLoaders: [
// Lint all js before compiling
/*{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}*/
],
loaders: [
{
test: /\.js$/,
query: {
presets: ['es2015']
},
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.tpl\.html$/,
exclude: /node_modules/,
loader: 'ngtemplate?relativeTo=/src/!html'
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.css$/,
loaders: ["style", "css"]
}
]
},
// Dev server settings
devServer: {
contentBase: path.join(__dirname, '/dist'),
noInfo: false,
hot: true
},
// ESLint config
eslint: {
configFile: path.join(__dirname, '.eslintrc')
}
};
My js files look like this
// app.js
let b = require('val!test.js');
// test.js
var process = require('process');
loadedModule = require(process.env.NODE_ENV) // NODE_ENV='./rawr.js'
export const myString = loadedModule
// rawr.js
module.exports.test = "hello world";
The exception I'm getting:
ERROR in ./src/app/app.js
Module parse failed: /home/smaug/Projects/angular-template/node_modules/babel-loader/index.js?{"presets":["es2015"]}!/home/smaug/Projects/angular-template/src/app/app.js Line 1: Unexpected identifier
You may need an appropriate loader to handle this file type.
| 'use strict';
|
| require('angular-animate');
# ./src/bootstrap.js 7:0-18
It has nothing to do with what I'm trying to do. But if I remove the require('val!...') statment, it goes away.
Any ideas?
UPDATE:
If I change the require statement to be
let b = require('val!./test.js');
I get the following error:
ERROR in ./~/val-loader!./src/app/test.js
Module build failed: Error: Final loader didn't return a Buffer or String
at DependenciesBlock.onModuleBuild (/home/smaug/Projects/angular-template/node_modules/webpack-core/lib/NormalModuleMixin.js:299:42)
at nextLoader (/home/smaug/Projects/angular-template/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
at /home/smaug/Projects/angular-template/node_modules/webpack-core/lib/NormalModuleMixin.js:292:15
at runSyncOrAsync (/home/smaug/Projects/angular-template/node_modules/webpack-core/lib/NormalModuleMixin.js:160:12)
at nextLoader (/home/smaug/Projects/angular-template/node_modules/webpack-core/lib/NormalModuleMixin.js:290:3)
at /home/smaug/Projects/angular-template/node_modules/webpack-core/lib/NormalModuleMixin.js:292:15
at Object.context.callback (/home/smaug/Projects/angular-template/node_modules/webpack-core/lib/NormalModuleMixin.js:148:14)
at Object.module.exports (/home/
// app.js
let b = require('val!./test.js');
This is a very confusing Error Message..
Check for the following mishaps..
import statement is pointing to the exact file;
typo errors in the file name on import statement; importing the
modules which are not present.
check whether you have installed all
the loaders like
css-loader node-sass resolve-url-loader sass-loader\
style-loader url-loader
4.import statement is empty
ex:
import * from '';
5. Services and Providers returning nothing may also cause this error.
test.js is supposed to return a string that contains the code that is supposed to be given to the module that is requiring it. So, for your example, test.js should go from this
var process = require('process');
loadedModule = require(process.env.NODE_ENV) // NODE_ENV='./rawr.js'
export const myString = loadedModule
to this
var process = require('process')
loadedModule = require('raw-loader!' + process.env.NODE_ENV)
export const myString = loadedModule
Using the "raw-loader" you will get the text code from rawr.js rather than the value that rawr.js exports. "val-loader" will then give rawr.js's code to the require in app.js and it will load that text as if it was the text of the file that you were trying to load.
That was probably a terrible explanation, but just remember that when you use val-loader, you need to return a string containing code.