Reputation: 2346
So I'm trying to set up a Fontend JS project using import
statements both for my custom components and for any node_modules
I'd like to use. (I'm sure there are other ways I could do this, but this is the way I'm trying to do it for this project.)
I keep reading that I just need some combination of webpack and babel-loader, but I'm still having trouble.
When testing lodash, and using an import like this: import lodash from 'lodash';
I get Failed to resolve module specifier "lodash". Relative references must start with either "/" ../etc
Directly importing the full path gave a 404, for ./node_modules/lodash/lodash.js
Here's my webpack.config.js
module.exports = {
entry: './src/app.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
contentBase: './src',
port: 9000,
historyApiFallback: {
index: 'index.html'
}
}
};
I've tried not exluding node_modules
and my babel.config.js
const presets = [
"@babel/preset-env"
];
const plugins = [
"@babel/plugin-proposal-class-properties"
];
Is there anything obvious I'm doing wrong?
I have much of this in a git repo here
Upvotes: 1
Views: 253
Reputation: 702
I checked your code and I found out your config is not creating an index.html
.
And the devServer.contentBase
is pointing to ./src
which is causing the error.
It should point to the output which is the ./dist
folder.
I updated your webpack config
var HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path')
module.exports = {
context: path.join(process.cwd(), 'src'),
entry: './app.js',
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}]
},
resolve: {
modules: [
path.join(process.cwd(), 'node_modules'),
]
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: 'index.html'
})
],
devServer: {
contentBase: './dist',
port: 9000,
overlay: true,
}
};
and on your index.html
, remove the script tag pointing to app.js
Upvotes: 1