I'm trying to get a basic ES6 import
/export
working with Webpack 4, and Webpack can't seem to resolve my module, though per the error message it's looking right at it:
$ make
./node_modules/.bin/webpack --mode production src/app.js -o dist/bundle.js
Hash: 6decf05b399fcbd42b01
Version: webpack 4.1.1
Time: 339ms
Built at: 2018-3-11 14:50:58
1 asset
Entrypoint main = bundle.js
[0] ./src/app.js 41 bytes {0} [built]
ERROR in ./src/app.js
Module not found: Error: Can't resolve 'hello.js' in '/home/(myhomedir)/code/js/src'
@ ./src/app.js 1:0-31 2:0-5
Here's my setup (node_modules
, dist
etc. omitted):
$ npm ls --depth=0
.
├── [email protected]
└── [email protected]
$ tree
.
├── Makefile
└── src
├── app.js
└── hello.js
Makefile:
webpack = ./node_modules/.bin/webpack --mode production
entry = src/app.js
webpack: $(entry)
$(webpack) $(entry) -o dist/bundle.js
src/app.js:
import {hello} from "hello.js";
hello();
src/hello.js:
function hello() {
alert("yes it's hello");
}
export { hello };
I've tried many variations on the import path in app.js
, but they all get the same result: Can't resolve
the module file. What am I missing?
You need to transpile it using babel & use babel-loader.
Also, you don't need to use make just use npm scripts.
There are mistakes like importing import { hello } from 'hello.js'
instead it should be import { hello } from './hello.js'
or without .js like import { hello } from './hello'
Try the following -
npm install --save-dev babel-core babel-loader babel-preset-env webpack@next webpack-cli
import { hello } from "./hello";
hello();
function hello() {
console.log("yes it's hello");
}
export { hello };
const path = require("path");
module.exports = {
entry: "./src/app.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
exclude: /(node_modules)/
}
]
}
};
{
"name": "webpack-test",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"build": "webpack --mode development",
"prod": "webpack --mode production",
"start": "node dist/bundle.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"webpack": "^4.0.0-beta.3",
"webpack-cli": "^2.0.11"
}
}
{
"presets": ["env"]
}
First run npm run build
or npm run prod
& then run npm run start
which will log the output