React Jest - Unexpected token import - reactjs

I'm learning react and I want to test one of my components but I'm stuck with this error:
{import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
Here's some things I have tried from reading post on stackoverflow and github
added test presets and these plugins "transform-es2015-modules-commonjs", dynamic-import-node" to my babel config
{
"presets": ["es2015", "react"],
"env": {
"test": {
"presets":[
["es2015", { "modules": false }],
"stage-0",
"react"],
"plugins": [
"transform-es2015-modules-commonjs",
"dynamic-import-node"
]
}
}
}
In my package.json the Jest property has these settings:
"jest": {
"verbose": true,
"moduleFileExtensions": [
"ts",
"tsx",
"jsx",
"js"
],
"transform": {},
"moduleDirectories": [
"node_modules"
],
"transformIgnorePatterns": [
"node_modules/(?!react)/"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
},
My actual component is built with ES6 and typescript if that helps you help me :)
From what I have read, it seems jest chokes on import because node doesn't understand ES6 import. None of the solutions I have tried online have seemed to work.
Also here are my dev Dependencies:
"devDependencies": {
"awesome-typescript-loader": "^3.2.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.4",
"enzyme": "^2.9.1",
"eslint": "^4.4.1",
"eslint-config-airbnb": "^15.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.2.0",
"extract-text-webpack-plugin": "^3.0.0",
"html-webpack-harddisk-plugin": "^0.1.0",
"html-webpack-plugin": "^2.30.1",
"jest": "^20.0.4",
"node-sass": "^4.5.3",
"react-test-renderer": "^15.6.1",
"regenerator-runtime": "^0.10.5",
"sass-loader": "^6.0.6",
"source-map-loader": "^0.2.1",
"style-loader": "^0.18.2",
"ts-jest": "^20.0.10",
"typescript": "^2.4.2",
"webpack": "^3.5.1",
"webpack-dev-middleware": "^1.12.0",
"webpack-dev-server": "^2.7.0"
},
Webpack config
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const HOST = "127.0.0.1";
const PORT = "9000";
const devServerUrl = "http://localhost:" + PORT + "/";
const config = {
devtool: 'source-map',
context: __dirname, // `__dirname` is root of project and `src` is source
entry:
[
'./src/index.js',
'./src/ui/styles.scss'
],
output: {
path: path.join(__dirname, 'dist'),
filename: "bundle.js",
publicPath: ''
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css']
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
{ test: /\.js$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{ test: /\.jsx$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
{
test: /\.(sass|scss)$/, use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
devServer: {
contentBase: "dist/",
noInfo: true,
inline: true,
compress: true,
port: PORT,
host: HOST,
hot: true
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html', // Output file name.
template: './public/index.html', // Use our HTML file as a template for the new one.
inject: 'body',
alwaysWriteToDisk: true,
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
}),
new ExtractTextPlugin({ // define where to save the file
filename: 'styles.bundle.css'}),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackHarddiskPlugin({
outputPath: path.resolve(__dirname, 'dist')
})
],
};
module.exports = config;
Thanks

Jest doesn't work with Typescript.
I have removed Jest from my project and installed Mocha, Karma, Chai & Enzyme.
Effortless to set up compared to Jest which masquerades as a:
Zero configuration testing platform
This article was a huge help: Getting Started on Testing with Typescript, ReactJS, and Webpack.
Hopefully this will save others from wasting their time getting Jest to work with Typescript.

It's because you have configured babel to not transpile ES6 modules
"presets":[
["es2015", { "modules": false }],
Try again with that modules to true (or omitted, since it defaults to true) and it should work.

you need to install babel to compile your es6 and react code
do it using
C:\Users\username\Desktop\reactApp>npm install babel-core
C:\Users\username\Desktop\reactApp>npm install babel-loader
C:\Users\username\Desktop\reactApp>npm install babel-preset-react
C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015
Try to keep our webpack as
var config = {
entry: './todoApp.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 9191
},
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;

Related

Error while configuring webpack 4 in my react (create-react-app) project

i am configuring the webpack 4 in my react project (create-react-app)
i have installed all the require loaders/file to configure my webpack, but there is always some different error, (some time its about sass-loader/css-loader/style-loader)
Now am dealing with (eot,woff,woff2,ttf) files error.
i don't know, i am conflicting the versions of node-sass/webpack/loaders or what.
please help me to configuring webpack in my project.
i am attaching the configuration files and errors screen.
Here is my devdependencies in my package-json file.
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"babel-loader": "^8.2.5",
"css-loader": "^3.6.0",
"file-loader": "^6.2.0",
"laravel-echo": "^1.11.2",
"less": "^4.1.2",
"less-loader": "^5.0.0",
"node-sass": "^4.14.1",
"pusher-js": "^7.0.3",
"raw-loader": "^4.0.2",
"react-error-overlay": "6.0.9",
"sass": "^1.51.0",
"sass-loader": "^7.1.0",
"style-loader": "^1.3.0",
"ts-loader": "^9.2.8",
"url-loader": "^4.1.1",
"webpack": "^4.42.0",
"webpack-cli": "^4.9.2"
}
webpack.config.js file
const path = require("path");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
publicPath: "/dist/",
},
// ...add the babel-loader and preset
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
// {
// test: /\.(scss|css|sass)$/,
// use: ["sass-loader", "style-loader", "css-loader"],
// },
{
test: /\.(scss|css|sass)$/,
use: [
// style-loader
{
loader: "style-loader",
},
// css-loader
{
loader: "css-loader",
options: {
modules: true,
},
},
// sass-loader
{
loader: "sass-loader",
options: {
modules: true,
},
},
],
},
{
test: /\.(woff2|woff|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
// options: {
// name: "[name].[ext]",
// outputPath: "fonts/",
// },
},
],
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: "file-loader",
},
],
},
],
},
// ...add resolve to .jsx extension
resolve: {
extensions: ["*", ".js", ".jsx"],
},
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Kindly check your themes scss and comment imports one by one and try to make build. In my case scss files were causing issues.

Webpack 4 Babel and React error in handling the JSX files

I keep getting this error, I tried several solutions using the search on this website and github but I cannot figure out what is wrong with it.
Here is what I have in my package.json
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
Here is my webpack config
module.export = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'main.js'
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
}
I created a .babelrc with this
{
"presets": ["env", "react", "es2015"]
}
Then I run
webpack-dev-server --mode development --hot
But if fails on this
ReactDOM.render(<App />, document.getElementById('app'));
This is the error I get in the console
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from './components/App';
|
> ReactDOM.render(<App />, document.getElementById('app'));
# multi (webpack)-dev-server/client?http://localhost:8080
(webpack)/hot/dev-server.js ./src main[2]
I spent 3 hours on google, stackoverflow and github but I cannot figure out what is wrong with this. Any help is highly appreciated.
Thanks!
Just throwing it there but you have
module.export
while it should be
module.exports
The issue is your config handles only files with .jsx but you also have .js file so, Change regex in webpack config and recompile your app
const path = require("path");
module.export = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
publicPath: "/
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
resolve: {
modules : [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: ['*', '.js', '.jsx']
}
}
replace your exiting modules with these dependencies
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.16.5",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
.babelrc
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}],
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}

Webpack3 unable to parse JSX files

I have the following configuration for a react based application that is failing JSX parsing during webpack build:
ERROR in ./src/App.jsx
Module parse failed: /Users/sangupta/git/plx/ui2/src/App.jsx Unexpected token (9:15)
You may need an appropriate loader to handle this file type.
|
| render() {
| return <div class='hello'>Hello World</div>;
| }
|
# multi (webpack)-dev-server/client?http://localhost:9000 webpack/hot/dev-server src/App.jsx
Any suggestions on what might be wrong?
The following is the package.json file:
{
"name": "Test-Project",
"version": "0.1.0",
"private": true,
"devDependencies": {
"autoprefixer": "6.4.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "0.28.4",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.30.1",
"less": "2.7.1",
"less-loader": "2.2.3",
"postcss-loader": "2.0.5",
"style-loader": "0.13.2",
"webpack": "3.4.1",
"webpack-dev-server": "2.6.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"scripts": {
"build": "webpack",
"build-production": "NODE_ENV=production npm run build",
"watch": "webpack-dev-server --hot --progress"
}
}
The following is webpack.config.json file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
context: __dirname,
entry: {
app: 'src/App.jsx',
vendor: [ "react", "react-dom" ]
},
devServer: {
contentBase: path.join(__dirname, 'assets'),
compress: true,
port: 9000,
hot: true,
https: false,
noInfo: false,
historyApiFallback: true
},
resolve: {
extensions: [ '.js', '.jsx' ],
alias: {
src: './src'
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js'
},
devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
module: {
rules: []
},
// Tell webpack to use html plugin
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new webpack.ProvidePlugin({
'React': 'react',
}),
new UglifyJsPlugin({ sourceMap: !isProduction }),
new HtmlWebpackPlugin({ title: 'MultiPLX', template: 'src/index.ejs', inject : 'body' })
]
};
You should be using the react babel preset:
npm install --save-dev babel-preset-react
webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "react", "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},

Having an issue when configuring HotModuleReplacement in webpack 2

I'm trying to integrate HotModuleReplacement and following this boilerplate, but is not working with my webpack configuration.
The "issue" I am having is in the output.publicPath entry. Following the example I mentioned, that line is "necessary for HMR to know where to load the hot update chunks", but when I include it in my webpack config it gives me this error GET http://localhost:3000/ 404 (Not Found). If I don't include it, webpack compiles everything successfully, but HMR does not work even though when I look at the console I get this
[WDS] App hot update...
dev-server.js:45 [HMR] Checking for updates on the server...
log-apply-result.js:20 [HMR] Updated modules:
log-apply-result.js:22 [HMR] - ./src/components/App.js
dev-server.js:27 [HMR] App is up to date.
Below is webpack.config.js file.
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index.js'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/static/'
},
devtool: 'inline-source-map',
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/, use: ['react-hot-loader/webpack', 'babel-loader'] },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ] },
{ test: /\.(png|jpg)$/, loader: 'file-loader?name=images/[name].[hash].[ext]' },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/font-woff'},
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/font-woff'},
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/octet-stream'},
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]'},
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=images/[name].[hash].[ext]&mimetype=image/svg+xml' }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({ template: 'public/index.html', favicon: 'public/favicon.ico' })
],
devServer: {
host: 'localhost',
port: 3000,
historyApiFallback: true,
hot: true
}
}
What am I missing?
These are my project dependencies just in case
"dependencies": {
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-prop-types": "^0.4.0",
"semantic-ui-css": "^2.2.10",
"semantic-ui-react": "^0.68.3"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"css-loader": "^0.28.1",
"file-loader": "^0.11.1",
"html-webpack-plugin": "^2.28.0",
"react-hot-loader": "next",
"style-loader": "^0.17.0",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
}
EDIT
I got it working. I changed publicPath to publicPath: '/' and added {"modules": false} to my .babelrc file
Below is my .babelrc file
{
"presets": [["env",{"modules": false}], "react", "stage-1"]
}
I guess I have a new question, what does {"modules": false} mean? what it is used for?
.babelrc is the configuration for the babel transpiler.
"Setting this to false will not transform modules.".
source: https://babeljs.io/docs/plugins/preset-es2015/#options

Webpack setup to bypass loading specific files with babel

I have a bootstrap theme that came with JS and CSS files that I'd like to integrate into my react app. I'm running into issues requiring the JS files because they don't export modules appropriately or properly define variables (using babel loader). I'd like to be able to require the JS in my app but not run them through babel. I'd also like to be able to use webpack's chunking and minification on these files if possible.
How do I go about setting this up?
Edit
I'm pretty sure what I need in reference to babel is the exclude config parameter. Unfortunately no matter what I try the exclude config isn't honored.
{
test: /\.js/,
loaders: [ 'react-hot', 'babel' ],
include: [
path.join(__dirname, 'src', 'app')
],
exclude: [
path.join(__dirname, 'src', 'semantic-v1.1.2')
]
},
Here's the error I receive:
ERROR in ./src/semantic-v1.1.2/assets/js/imagesloaded.pkgd.js
Module not found: Error: Cannot resolve module 'eventEmitter' in /Users/bradr/Dropbox (Personal)/Development/ritasfoods-com/src/semantic-v1.1.2/assets/js
# ./src/semantic-v1.1.2/assets/js/imagesloaded.pkgd.js 731:2-735:24
I'm sure I'm missing something simple.
Full webpack.config.js:
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./src/app/index'
],
output: {
path: path.join(__dirname, 'static'),
filename: 'bundle.js',
publicPath: '/static/'
},
module: {
noParse: [
/aws\-sdk/, // Hack to be able to import aws sdk.
],
loaders: [
{
test: /\.js/,
loaders: [ 'react-hot', 'babel' ],
include: path.join(__dirname, 'src/app'),
exclude: path.resolve('src', 'semantic-v1.1.2')
},
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.md$/, loader: "html!markdown?gfm=false" },
{ test: /\.html/, loader: 'html' },
{ test: /\.yaml/, loader: 'json!yaml' },
{ test: /\.(woff|woff2)$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf$/, loader: "file-loader" },
{ test: /\.eot$/, loader: "file-loader" },
{ test: /\.svg$/, loader: "file-loader" },
{ test: /\.(jpg|png)$/, loader: 'url' }
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
resolve: {
// Removes the need to specify file type in imports.
extensions: ['', '.js', '.json'],
alias:{
theme: path.resolve( __dirname, 'src', 'semantic-v1.1.2', 'assets')
}
}
};
.babelrc
{
"presets": ["es2015", "stage-0", "react"],
}
package.json
{
"name": "ritasfoods-com",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": true,
"scripts": {
"start": "node server.js",
"build-prod": "./node_modules/webpack/bin/webpack.js -p --config webpack.config.prod.js --progress --colors",
"deploy-prod": "ops/deploy-prod"
},
"repository": {
"type": "git",
"url": "..."
},
"author": "Brad Reynolds",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.6.0",
"babel-loader": "^6.2.4",
"babel-plugin-transform-class-properties": "^6.6.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.23.1",
"html-loader": "^0.4.3",
"node-sass": "^3.4.2",
"react-hot-loader": "^1.3.0",
"redux-devtools": "^3.2.0",
"redux-devtools-dock-monitor": "^1.1.1",
"redux-devtools-log-monitor": "^1.0.11",
"sass-loader": "^3.1.2",
"style-loader": "^0.13.1",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"aws-sdk": "^2.2.40",
"babel-polyfill": "^6.8.0",
"babel-preset-stage-0": "^6.5.0",
"es6-promise": "^3.1.2",
"events": "^1.1.0",
"exports-loader": "^0.6.3",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.8.5",
"html-loader": "^0.4.3",
"imports-loader": "^0.6.5",
"invariant": "^2.2.1",
"jquery": "^2.2.1",
"less": "^2.6.1",
"less-loader": "^2.2.3",
"markdown-loader": "^0.1.7",
"mustache": "^2.2.1",
"numeral": "^1.5.3",
"pluralize": "^1.2.1",
"react": "15.0.1",
"react-dom": "15.0.1",
"react-redux": "^4.4.5",
"react-router": "^2.0.0",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-thunk": "^2.0.1",
"url-loader": "^0.5.7"
}
}
server.js
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config.js');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(8080, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:8080/');
});
I bit the bullet and installed every JS file from the bootstrap theme via npm. It was a PITA as I had to configure a few via webpack. But it's done so I can move on.
I do this for image assets for a chrome extension. The app itself doesn't use them, but Chrome does, so I need them copied into the build folder.
Create an extra entry for static files. Your entry is a js file that just requires all the static files. You will end up with a useless extra bundle as a byproduct, but all your files will be copied over to your build folder.
I'll show you the example of images first because I have working code to pull that from.
webpackconfig.js
// ...
entry: {
// ...
'img': './img/index.js'
},
output: {
// dynamic bundle name for multiple outputs
filename: '[name].js'
// ...
},
rules: {
// ...
{
test: /\.png|svg|jpg|gif$/,
use: [
{
// copy loaded files to
// output_base_path/input_relative_path/filename.extension
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
useRelative: true
}
},
{
loader: 'image-webpack-loader',
options: { /* ... */ }
}
]
}
}
src/img/index.js
// This is the only line in this file.
// Recursively require all png or jpg from current folder
require.context('./', true, /\.(png|jpg)$/)
So now I'll get speculative and try to translate it to your use-case as best I can without being able to test it:
webpackconfig.js
// ...
entry: {
// ...
'static': './static/index.js'
},
output: {
filename: '[name].js'
// ...
},
rules: {
// ...
{
// I'm guessing the string being tested here is a relative path.
// If I'm wrong, this regex will need some tweaking.
// Matches everything in assets folder
test: /^assets\/.+/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
useRelative: true
}
},
{
// Not sure if you actually need this loader, but it's something I
// would try if file loader is choking on your files, especially
// if you are processing multiple filetypes.
loader: 'raw-loader'
}
]
}
}
src/assets/index.js
// Let's just match everything. Putting images in this folder will
// probably give you headaches. Limit it to text files and handle images
// separately.
require.context('./', true, /.+/)
Here's some info on require.context and file-loader

Resources