diff --git a/packages/gatsby/src/utils/__tests__/webpack-utils.js b/packages/gatsby/src/utils/__tests__/webpack-utils.js new file mode 100644 index 0000000000000..ba6065120c6b1 --- /dev/null +++ b/packages/gatsby/src/utils/__tests__/webpack-utils.js @@ -0,0 +1,29 @@ +const utils = require(`../webpack-utils`) + +let config +beforeAll(async () => { + config = await utils({ + stage: `develop`, + program: { + browserslist: [], + }, + }) +}) + +describe(`webpack utils`, () => { + describe(`mjs`, () => { + it(`adds .mjs rule`, () => { + expect(config.rules.mjs).toEqual(expect.any(Function)) + }) + + it(`returns correct rule`, () => { + const rule = config.rules.mjs() + + expect(rule).toEqual({ + include: /node_modules/, + test: /\.mjs$/, + type: `javascript/auto`, + }) + }) + }) +}) diff --git a/packages/gatsby/src/utils/webpack-utils.js b/packages/gatsby/src/utils/webpack-utils.js index 0806a2842a5c9..53da359b5be42 100644 --- a/packages/gatsby/src/utils/webpack-utils.js +++ b/packages/gatsby/src/utils/webpack-utils.js @@ -296,6 +296,25 @@ module.exports = async ({ rules.js = js } + /** + * mjs loader: + * webpack 4 has issues automatically dealing with + * the .mjs extension, thus we need to explicitly + * add this rule to use the default webpack js loader + */ + { + let mjs = (options = {}) => { + return { + test: /\.mjs$/, + include: /node_modules/, + type: `javascript/auto`, + ...options, + } + } + + rules.mjs = mjs + } + { let eslint = schema => { return { diff --git a/packages/gatsby/src/utils/webpack.config.js b/packages/gatsby/src/utils/webpack.config.js index e5b1603a14e77..6aa29a3771d13 100644 --- a/packages/gatsby/src/utils/webpack.config.js +++ b/packages/gatsby/src/utils/webpack.config.js @@ -285,6 +285,7 @@ module.exports = async ( // Common config for every env. // prettier-ignore let configRules = [ + rules.mjs(), rules.js(), rules.yaml(), rules.fonts(), @@ -359,10 +360,7 @@ module.exports = async ( // modules. But also make it possible to install modules within the src // directory if you need to install a specific version of a module for a // part of your site. - modules: [ - directoryPath(path.join(`node_modules`)), - `node_modules`, - ], + modules: [directoryPath(path.join(`node_modules`)), `node_modules`], alias: { gatsby$: directoryPath(path.join(`.cache`, `gatsby-browser-entry.js`)), // Using directories for module resolution is mandatory because