@nicolas-marien
I have encountered the same error. Here is the repro project:
vue-webpack-test.zip
Here is my webpack config:
const path = require('path') const { VueLoaderPlugin } = require('vue-loader') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode: 'development', entry: { main: './src/main.js', }, devServer: { hot: true, }, module: { rules: [ { test: /.vue$/, use: 'vue-loader' }, { test: /.css$/, use: [ 'vue-style-loader', { loader: 'css-loader', options: { esModule: false } }, ] }, { test: /.scss$/, use: [ 'vue-style-loader', { loader: 'css-loader', options: { esModule: false } }, 'sass-loader' ] }, { test: /.js$/, exclude: /core-js/, use: 'babel-loader' } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title: 'Vue + Webpack test', template: 'public/index.html', scriptLoading: 'blocking' }), new VueLoaderPlugin() ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), } }
Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ./assets/js/jquery/interview.js
I get this error when I try to export a function with module.exports and when I import it inside another file. I tried to use export default but the JS file that calls the original file can’t find any method. I also found this topic
https://github.com/babel/babel/issues/12731 but I don’t have a babel.config.json file…
Here is my code :
Interview.prototype = function ($) {
const collapseLocalStoredElements = function (localStorageId) {
let collapseItemsIds = localStorage.getItem(localStorageId);
console.log(collapseItemsIds)
}
return {
collapseLocalStoredElements: collapseLocalStoredElements,
};
}(jQuery);
// export default Interview;
module.exports = Interview;
App.js
//Import
let InterviewImport = require ('./js/jquery/interview');
//Uses
let Interview = new InterviewImport();
console.log(Interview.collapseLocalStoredElements('collapseItemsIds'));
Thanks!!
asked Oct 21, 2022 at 9:25
MrsStormMrsStorm
231 silver badge5 bronze badges
Try using ESM syntax.
export default Interview;
App.js
Import Interview from ('./js/jquery/interview');
There also seem to be one too many closing brackets in your code, I’ve removed the one that I think was unnecessary. The function also seems to be self-executing. You might want to remove that.
Interview.prototype = function (localStorageId) {
let collapseItemsIds = localStorage.getItem(localStorageId);
console.log(collapseItemsIds);
};
answered Oct 21, 2022 at 9:32
Fralle♦Fralle
8516 silver badges11 bronze badges
4
Before opening, please confirm:
- I have searched for duplicate or closed issues and discussions.
- I have read the guide for submitting bug reports.
- I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.
JavaScript Framework
React
Amplify APIs
Storage
Amplify Categories
storage
Environment information
# Put output below this line
[2D40:0B30][2021-11-18T13:01:59]i001: Burn v3.10.4.4718, Windows v10.0 (Build 19042: Service Pack 0), path: C:WindowsTemp{A17C2DB6-A61A-4C3D-86BE-75E0623BE8C7}.crVC_redist.x64.exe
[2D40:0B30][2021-11-18T13:01:59]i009: Command Line: '-burn.clean.room=C:ProgramDataMicrosoftVisualStudioPackagesMicrosoft.VisualCpp.Redist.14.Latest,version=14.30.30704,chip=x64VC_redist.x64.exe -burn.filehandle.attached=520 -burn.filehandle.self=628 /q /norestart /log C:UsersDESKTOP 10AppDataLocalTempdd_setup_20211118125756_046_Microsoft.VisualCpp.Redist.14.Latest.log'
[2D40:0B30][2021-11-18T13:01:59]i000: Setting string variable 'WixBundleOriginalSource' to value 'C:ProgramDataMicrosoftVisualStudioPackagesMicrosoft.VisualCpp.Redist.14.Latest,version=14.30.30704,chip=x64VC_redist.x64.exe'
[2D40:0B30][2021-11-18T13:01:59]i000: Setting string variable 'WixBundleOriginalSourceFolder' to value 'C:ProgramDataMicrosoftVisualStudioPackagesMicrosoft.VisualCpp.Redist.14.Latest,version=14.30.30704,chip=x64'
[2D40:0B30][2021-11-18T13:01:59]i000: Setting string variable 'WixBundleLog' to value 'C:UsersDESKTOP'
[2D40:0B30][2021-11-18T13:01:59]i000: Setting string variable 'WixBundleManufacturer' to value 'Microsoft Corporation'
[2D40:04E0][2021-11-18T13:01:59]i000: Setting version variable 'WixBundleFileVersion' to value '14.30.30704.0'
[2D40:0B30][2021-11-18T13:01:59]i100: Detect begin, 11 packages
[2D40:0B30][2021-11-18T13:01:59]i000: Setting string variable 'Arm64_Check' to value 'AMD64'
[2D40:0B30][2021-11-18T13:01:59]i000: Setting version variable 'windows_uCRT_DetectKey' to value '10.0.19041.546'
[2D40:0B30][2021-11-18T13:01:59]i000: Setting numeric variable 'windows_uCRT_DetectKeyExists' to value 1
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.3 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.3 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.2 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.2 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.1 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.1 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.0 AND NOT VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT = v6.0 AND VersionNT64) AND (windows_uCRT_DetectKeyExists AND windows_uCRT_DetectKey >= v10.0.10240.0)' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: Windows81_x86, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: Windows81_x64, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: Windows8_x86, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: Windows8_x64, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: Windows7_MSU_x86, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: Windows7_MSU_x64, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: WindowsVista_MSU_x86, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: WindowsVista_MSU_x64, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: vcRuntimeMinimum_x64, state: Present, cached: Complete
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: vcRuntimeAdditional_x64, state: Present, cached: Complete
[2D40:0B30][2021-11-18T13:01:59]i101: Detected package: vcRuntime_arm64, state: Absent, cached: None
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT >= v6.1 OR (VersionNT = v6.0 AND ServicePackLevel >= 2)' evaluates to true.
[2D40:0B30][2021-11-18T13:01:59]i199: Detect complete, result: 0x0
[2D40:0B30][2021-11-18T13:01:59]i200: Plan begin, 11 packages, action: Modify
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.3 AND NOT VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: Windows81_x86
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.3 AND VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: Windows81_x64
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.2 AND NOT VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: Windows8_x86
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.2 AND VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: Windows8_x64
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.1 AND NOT VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: Windows7_MSU_x86
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.1 AND VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: Windows7_MSU_x64
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.0 AND NOT VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: WindowsVista_MSU_x86
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'VersionNT = v6.0 AND VersionNT64' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]w321: Skipping dependency registration on package with no dependency providers: WindowsVista_MSU_x64
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT64) AND NOT (Arm64_Check = "ARM64")' evaluates to true.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition '(VersionNT64) AND NOT (Arm64_Check = "ARM64")' evaluates to true.
[2D40:0B30][2021-11-18T13:01:59]i052: Condition 'Arm64_Check = "ARM64"' evaluates to false.
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: Windows81_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: Windows81_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: Windows8_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: Windows8_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: Windows7_MSU_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: Windows7_MSU_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: WindowsVista_MSU_x86, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: WindowsVista_MSU_x64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: vcRuntimeMinimum_x64, state: Present, default requested: Present, ba requested: Present, execute: None, rollback: None, cache: No, uncache: No, dependency: Register
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: vcRuntimeAdditional_x64, state: Present, default requested: Present, ba requested: Present, execute: None, rollback: None, cache: No, uncache: No, dependency: Register
[2D40:0B30][2021-11-18T13:01:59]i201: Planned package: vcRuntime_arm64, state: Absent, default requested: Absent, ba requested: Absent, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[2D40:0B30][2021-11-18T13:01:59]i299: Plan complete, result: 0x0
[2D40:0B30][2021-11-18T13:01:59]i300: Apply begin
[2D40:0B30][2021-11-18T13:01:59]i010: Launching elevated engine process.
[2D40:0B30][2021-11-18T13:01:59]i011: Launched elevated engine process.
[2D40:0B30][2021-11-18T13:01:59]i012: Connected to elevated engine.
[1038:09C0][2021-11-18T13:01:59]i358: Pausing automatic updates.
[1038:09C0][2021-11-18T13:01:59]i359: Paused automatic updates.
[1038:09C0][2021-11-18T13:01:59]i360: Creating a system restore point.
[1038:09C0][2021-11-18T13:01:59]i361: Created a system restore point.
[1038:09C0][2021-11-18T13:01:59]i371: Updating session, registration key: SOFTWAREMicrosoftWindowsCurrentVersionUninstall{57a73df6-4ba9-4c1d-bbbb-517289ff6c13}, resume: Active, restart initiated: No, disable resume: No
[1038:09C0][2021-11-18T13:01:59]i325: Registering dependency: {57a73df6-4ba9-4c1d-bbbb-517289ff6c13} on package provider: Microsoft.VS.VC_RuntimeMinimumVSU_amd64,v14, package: vcRuntimeMinimum_x64
[1038:09C0][2021-11-18T13:01:59]i325: Registering dependency: {57a73df6-4ba9-4c1d-bbbb-517289ff6c13} on package provider: Microsoft.VS.VC_RuntimeAdditionalVSU_amd64,v14, package: vcRuntimeAdditional_x64
[1038:09C0][2021-11-18T13:01:59]i372: Session end, registration key: SOFTWAREMicrosoftWindowsCurrentVersionUninstall{57a73df6-4ba9-4c1d-bbbb-517289ff6c13}, resume: ARP, restart: None, disable resume: No
[1038:09C0][2021-11-18T13:01:59]i371: Updating session, registration key: SOFTWAREMicrosoftWindowsCurrentVersionUninstall{57a73df6-4ba9-4c1d-bbbb-517289ff6c13}, resume: ARP, restart initiated: No, disable resume: No
[2D40:0B30][2021-11-18T13:01:59]i399: Apply complete, result: 0x0, restart: None, ba requested restart: No
[2D40:0B30][2021-11-18T13:01:59]i500: Shutting down, exit code: 0x0
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: Arm64_Check = AMD64
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: SystemFolder = C:Windowssystem32
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: VersionNT = 10.0.0.0
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: VersionNT64 = 10.0.0.0
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: windows_uCRT_DetectKey = 10.0.19041.546
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: windows_uCRT_DetectKeyExists = 1
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleAction = 6
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleElevated = 1
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleFileVersion = 14.30.30704.0
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleInstalled = 1
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleLog = C:UsersDESKTOP
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleManufacturer = Microsoft Corporation
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleName = Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.30.30704
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleOriginalSource = C:UsersDESKTOP 10AppDataLocalTempchocolateyvcredist14014.30.30704VC_redist.x64.exe
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleOriginalSourceFolder = C:UsersDESKTOP 10AppDataLocalTempchocolateyvcredist14014.30.30704
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleProviderKey = VC,redist.x64,amd64,14.30,bundle
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleSourceProcessFolder = C:ProgramDataMicrosoftVisualStudioPackagesMicrosoft.VisualCpp.Redist.14.Latest,version=14.30.30704,chip=x64
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleSourceProcessPath = C:ProgramDataMicrosoftVisualStudioPackagesMicrosoft.VisualCpp.Redist.14.Latest,version=14.30.30704,chip=x64VC_redist.x64.exe
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleTag =
[2D40:0B30][2021-11-18T13:01:59]i410: Variable: WixBundleVersion = 14.30.30704.0
[2D40:0B30][2021-11-18T13:01:59]i007: Exit code: 0x0, restarting: No
Describe the bug
React production build unable to render react prod build showing this error.
Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 44168
with below code:
import Storage from '@aws-amplify/storage';
// Note also tried with
// import { Storage } from '@aws-amplify/storage';
class StorageService {
public uploadFile(file: File): Promise<any> {
return Storage.put(file.name, file, {
resumable: false,
progressCallback: progress => {
console.log(`Uploaded: ${progress.loaded}/${progress.total}`);
},
});
}
}
const instance = new StorageService();
export default instance;
Note: This build working fine in dev mode yarn start
no render error that’s why I’m unable to find the root cause.
and when I comment the Storage import statement then it start working again.
Expected behavior
it should work properly with prod and dev environments
Reproduction steps
- create new react app with typescript template.
- install aws-amplify and configure it.
- Implement above code example available in Describe the bug section.
- Now test functionality with start it will work fine.
- Create Production build now you get the the error message.
Code Snippet
// Put your code below this line. import { Storage } from '@aws-amplify/storage'; class StorageService { public uploadFile(file: File): Promise<any> { return Storage.put(file.name, file, { resumable: false, progressCallback: progress => { console.log(`Uploaded: ${progress.loaded}/${progress.total}`); }, }); } } const instance = new StorageService(); export default instance;
Log output
// Put your logs below this line
harmony module decorator:7 Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 44168
at Object.set [as exports] (harmony module decorator:7)
at Module.44168 (json2xml.js:280)
at r (bootstrap:19)
at Object.86019 (parser.js:37)
at r (bootstrap:19)
at Object.74984 (XmlText.ts:6)
at r (bootstrap:19)
at Object.79974 (Link.js:182)
at r (bootstrap:19)
at CssBaseline.js:59
aws-exports.js
No response
Manual configuration
No response
Additional configuration
No response
Mobile Device
No response
Mobile Operating System
No response
Mobile Browser
No response
Mobile Browser Version
No response
Additional information and screenshots
No response
Bug Report
Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 581
Current behavior
Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 581
Expected behavior
There is no abnormal
Environment
webpack version: «webpack»: «^5.13.0»,
Node.js version: v10.15.3
Operating System: mac
Additional tools:vscode
«@babel/core»: «^7.12.10»,
«@babel/preset-env»: «^7.12.11»,
Possible Solution
Additional context
babel.config.js:
module.exports = {
presets: [
[
'@babel/preset-env',
{
corejs: 2,
useBuiltIns: 'usage'
}
],
'@vue/babel-preset-jsx'
],
plugins: []
}
Asked Oct 13 ’21 01:10
takhello
8 Answer:
Hey @takhello! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we’re a limited number of volunteers, so it’s possible this won’t be addressed swiftly.
If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite.»
1
Answered Feb 01 ’21 at 03:01
babel-bot
This error is not thrown by Babel, but by webpack. Can you post your webpack config?
1
Answered Feb 01 ’21 at 21:07
nicolo-ribaudo
@nicolas-marien
I have encountered the same error. Here is the repro project:
vue-webpack-test.zip
Here is my webpack config:
const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
main: './src/main.js',
},
devServer: {
hot: true,
},
module: {
rules: [
{
test: /.vue$/,
use: 'vue-loader'
},
{
test: /.css$/,
use: [
'vue-style-loader',
{
loader: 'css-loader',
options: {
esModule: false
}
},
]
},
{
test: /.scss$/,
use: [
'vue-style-loader',
{
loader: 'css-loader',
options: {
esModule: false
}
},
'sass-loader'
]
},
{
test: /.js$/,
exclude: /core-js/,
use: 'babel-loader'
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Vue + Webpack test',
template: 'public/index.html',
scriptLoading: 'blocking'
}),
new VueLoaderPlugin()
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
}
}
1
Answered Feb 16 ’21 at 18:14
Mikilll94
@nicolo-ribaudo
This is not a bug during build time. You need to run the app. Please execute:
npm install
npm run dev
Then go to localhost:8080, open devtools and you will see this bug.
1
Answered Feb 16 ’21 at 22:15
Mikilll94
@Mikilll94 Adding sourceType: "unambiguous"
to babel.config.js
seems to fix the error.
"umabiguous"
tells Babel to automatically detect if it’s transforming a CJS or ESM file, so that it doesn’t inject import
statements in CJS dependencies.
Then there is another error (process is not defined
), but it seems unrelated.
1
Answered Feb 16 ’21 at 22:18
nicolo-ribaudo
@nicolo-ribaudo
Thanks, I confirm that adding sourceType: "unambiguous"
fixes the error.
However, I don’t have this bug process is not defined
. Could you check this again?
1
Answered Feb 16 ’21 at 23:27
Mikilll94
Oh I don’t see process is not defined
anymore, maybe it was something else I changed :thinking:
Anyway, I’m now going to close this issue since we don’t have the webpack config for the OP, so I can just assume that it was the same problem as you had!
1
Answered Feb 16 ’21 at 23:32
nicolo-ribaudo
Adding "sourceType": "unambiguous"
to my babel.config.json fixed the issue
«`
babel.config.json
{
«sourceType»: «unambiguous»,
«plugins»: [«@babel/plugin-transform-runtime»],
«presets»: [«@babel/preset-env»]
}
webpack.config.js
{
test: /.js$/,
exclude: /(nodemodules|bowercomponents)/,
use: {
loader: ‘babel-loader’,
options: {
presets: [‘@babel/preset-env’],
plugins: [‘@babel/plugin-transform-runtime’]
}
}
}
«`
Thank you so much!
1
Answered Apr 14 ’21 at 01:32
wfabio
Bug report
Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 581
What is the current behavior?
Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 581
What is the expected behavior?
There is no abnormal
Other relevant information:
webpack version: «webpack»: «^5.13.0»,
Node.js version: v10.15.3
Operating System: mac
Additional tools:vscode
For maintainers only:
- webpack-4
- webpack-5
- bug
- critical-bug
- enhancement
- documentation
- performance
- dependencies
- question
You need to fix the code of module 581.
module.exports
must not be assigned within an ESM.
Try development mode for the readable module name.
Sometimes this is also caused by incorrect Babel config, which inserts imports which converts the module to an ESM.
Answer above, feel free to feedback
Keep it here just in case someone faces the same issue.
For me this error happens on a CommonJS module only when I use typeof
operator in the prototype method and compare typeof result to a variable, not a string constant.
E.g.
ItemQuantityController.prototype.isTypeOrNullable = function(type, value) { // return true; return typeof value === type || value === null; };
I managed to fix it with replacing type
variable in the comparison with its string equivalent ${type}
.
This may have something to do with how Babel transforms typeof
but I was not successful googling any clue to the culprit so I just keep the solution here.
@WhereJuly Please create reproducible test repo, I will open an issue if it will be bug
I had same issure but "sourceType": "unambiguous",
not work.
Because I tentatively edited a node-style module, i copied a line with es-style require:
import { app } from "electron"; // the ruin
var fs = require('fs')
var path = require('path')
var os = require('os')
This may have something to do with how Babel transforms
typeof
but I was not successful googling any clue to the culprit so I just keep the solution here.
Yeah, this can happen if you’re using babel-plugin-transform-runtime along with babel’s sourceType: 'module'
.
babel-plugin-transform-runtime is inserting an import statement into the file, which causes webpack to treat the file as an ES module, which causes it to be an error to try to assign to module.exports
.
Using Webpack with the Serverless Framework is handy if you want to use the latest Javascript features along with Babel. It also helps to optimize the packaging of functions so we can make sure we’re only shipping code that is lean and mean. However, adding the delightful query builder Knex to the mix can cause some issues that I spent a good amount of time on. Hopefully this article will help anyone dealing with similar issues save some time.
In this article we’ll go through setting up a Serverless project with Webpack, Babel, and Knex along with Prettier and Eslint. We’ll focus on specific issues with Knex in this scenario and how to solve them. If you want a TLDR; here’s the final output, a Serverless starter template with Webpack, Babel, and Knex ready to go.
Project Setup
Install serverless globally
npm install serverless -g
Enter fullscreen mode
Exit fullscreen mode
First, we’ll set up a new Serverless project using a default aws-nodejs template:
serverless create --template aws-nodejs
Enter fullscreen mode
Exit fullscreen mode
This will create a bare handler.js and a serverless yaml file to get us started.
Next add a package.json file to manage our dependencies
npm init -y
Enter fullscreen mode
Exit fullscreen mode
Add Dev Dependencies and Webpack:
We’re going to add Babel to get access to the latest Javascript features and then we’ll add Webpack to transform our Javascript code in a way that the Serverless platforms (AWS) can handle. We’ll also add Serverless-Offline which emulates AWS and AWS Gateway, allowing us to run our functions locally.
npm install --save-dev @babel/core @babel/preset-env webpack serverless-webpack serverless-offline babel-loader dotenv
Enter fullscreen mode
Exit fullscreen mode
Adding Source Map Support
It’s always nice to get stack traces, let’s set up source map support.
npm install source-map-support --save npm install
babel-plugin-source-map-support --save-dev
Enter fullscreen mode
Exit fullscreen mode
The source-map-support module provides source map support for stack traces in node via the V8 stack trace API
Babel-plugin-source-map-support prepends this statement to each file, giving us stack traces with the source-map-support package:
import 'source-map-support/register';
Setting up Babel
Create a .babelrc file in the root of the project to handle our Babel configuration:
.babelrc
{
"plugins": ["source-map-support"],
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": true
}
}
]
]
}
Enter fullscreen mode
Exit fullscreen mode
Adding Knex
Next, we’ll add Knex and MySQL as the driver of choice for this purpose:
npm install --save mysql2 knex
Enter fullscreen mode
Exit fullscreen mode
Setting up Knex
Create a knexfile.js in the project root:
import dotenv from "dotenv";
dotenv.config({ silent: true });
module.exports = {
development: {
client: "mysql2",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PW,
database: process.env.DB_DB
}
// migrations: {
// directory: './database/migrations',
// },
// seeds: { directory: './database/seeds' }
},
staging: {
client: "mysql2",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PW,
database: process.env.DB_DB
}
},
production: {
client: "mysql2",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PW,
database: process.env.DB_DB
}
}
};
Enter fullscreen mode
Exit fullscreen mode
Create a folder called queries in your project root, this will be where the data retrieval functions will go:
mkdir queries
Enter fullscreen mode
Exit fullscreen mode
Add a knex file:
knex.js
const knex = require("knex");
const knexfile = require("../knexfile");
const env = process.env.NODE_ENV || "development";
const configOptions = knexfile[env];
module.exports = knex(configOptions);
Enter fullscreen mode
Exit fullscreen mode
Example query file — games.js:
const knex = require("./knex");
export async function getAll() {
const res = await knex("matches").select("*");
return res;
}
Enter fullscreen mode
Exit fullscreen mode
Setting up Webpack
In the root of the project create a webpack.config.js file and configure Webpack to use Babel to bundle up our Serverless functions.
We’ll also exclude node development dependencies using the node externals package.
npm install webpack-node-externals --save-dev
Enter fullscreen mode
Exit fullscreen mode
webpack.config.js:
const slsw = require("serverless-webpack");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: slsw.lib.entries,
devtool: "source-map",
// Since 'aws-sdk' is not compatible with webpack,
// we exclude all node dependencies
externalsPresets: { node: true },
externals: [nodeExternals()],
mode: slsw.lib.webpack.isLocal ? "development" : "production",
optimization: {
minimize: false
},
performance: {
// Turn off size warnings for entry points
hints: false
},
// Run babel on all .js files - skip those in node_modules
module: {
rules: [
{
test: /.js$/,
loader: "babel-loader",
include: __dirname,
exclude: /node_modules/
}
]
},
plugins: []
};
Enter fullscreen mode
Exit fullscreen mode
Setting up Serverless
Add our plugins to the serverless.yaml file:
- serverless-webpack
- serverless-offline
Enter fullscreen mode
Exit fullscreen mode
Add serverless-webpack configuration to serverless.yaml
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules: true # enable auto-packing of external modules
Enter fullscreen mode
Exit fullscreen mode
We’ll add an http endpoint to the default hello handler, so that we can test our api endpoint out:
events:
- http:
path: hello
method: get
cors: true
Enter fullscreen mode
Exit fullscreen mode
Full Serverless.yaml
service: serverless-webpack-babel-knex-starter
frameworkVersion: "2"
provider:
name: aws
runtime: nodejs12.x
apiGateway:
shouldStartNameWithService: true
plugins:
- serverless-webpack
- serverless-offline
functions:
hello:
handler: handler.hello
events:
- http:
path: hello
method: get
cors: true
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules: true # enable auto-packing of external modules
Enter fullscreen mode
Exit fullscreen mode
Running and Knex Issues
Let’s test it out!
Add a start npm script to package.json
"start": "serverless offline start --stage dev --noAuth"
Enter fullscreen mode
Exit fullscreen mode
Call our API
curl --location --request GET 'http://localhost:3000/dev/hello'
Enter fullscreen mode
Exit fullscreen mode
Knex Runtime Issues:
- ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ./knexfile.js
It doesn’t like that we’re using module.exports in our knexfile, one potential solution would be to use es6 default export syntax
export default {}
This ended up causing more problems then it solved dealing with the internal knex library which doesn’t play well with ES modules.
The solution I went for is to use a Babel plugin to transform ESM to CommonJS Modules which is the standard for Node modules. Client-side JavaScript that runs in the browser use another standard, called ES Modules or ESM.
In CommonJS, we export with module.exports and import with require statements. Since we’re using Babel we can use import/export and our code will be transformed into CommonJS modules.
npm install --save-dev @babel/plugin-transform-modules-commonjs
Enter fullscreen mode
Exit fullscreen mode
Add to our plugins section in .babelrc
{
"plugins": ["source-map-support", "@babel/plugin-transform-modules-commonjs"],
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": true
}
}
]
]
}
Enter fullscreen mode
Exit fullscreen mode
Using CommonJS should be enough to get you going but you might run into the next issue:
- Can’t resolve runtime dependencies
Module not found: Error: Can't resolve 'oracledb'
Module not found: Error: Can't resolve 'pg-native'
Module not found: Error: Can't resolve 'pg-query-stream'
Module not found: Error: Can't resolve 'sqlite3'
Enter fullscreen mode
Exit fullscreen mode
If you receive module not found errors for packages that you are not using, then we can fix this by ignoring those drivers/packages.
There are different ways this can be approached with Webpack and with Serverless but the solution that I landed on was to use the NormalModuleReplacementPlugin which is bundled with Webpack. This plugin allows you to replace resources that match a regular expression with another resource. We’ll add the noop2 package to replace the drivers we’re not using with a «no operation module».
npm install --save-dev noop2
Enter fullscreen mode
Exit fullscreen mode
const { NormalModuleReplacementPlugin } = require("webpack");
plugins: [
// Ignore knex runtime drivers that we don't use
new NormalModuleReplacementPlugin(
/mssql?|oracle(db)?|sqlite3|pg-(native|query)/,
"noop2"
)
];
Enter fullscreen mode
Exit fullscreen mode
Adding Eslint and Prettier
To finish this starter template, we’ll add some niceness to the project with eslint and prettier.
npm install --save-dev @babel/eslint-parser eslint eslint-config-prettier eslint-plugin-lodash eslint-plugin-prettier prettier
Enter fullscreen mode
Exit fullscreen mode
prettierrc.json
{
"trailingComma": "none",
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"printWidth": 120
}
Enter fullscreen mode
Exit fullscreen mode
.eslintrc.js
module.exports = {
env: {
node: true
},
plugins: ["prettier"],
parser: "@babel/eslint-parser",
parserOptions: {
sourceType: "module",
ecmaFeatures: {
classes: true,
experimentalObjectRestSpread: true
}
},
extends: [
"eslint:recommended",
"plugin:prettier/recommended",
"plugin:lodash/recommended"
],
rules: {
"prettier/prettier": "error"
}
};
Enter fullscreen mode
Exit fullscreen mode
Starter Project
Now we have a nice starter project to get us off the ground with Serverless, Webpack, Babel, and Knex.
To grab all this goodness or if you have improvements, check out the Github
repository