Greetings one and all,
After having made a React application, I decided to dive in deeper into Webpack.
I am rather new at the whole npm automation scene and after having followed a cookbook and various tutorials, I just cannot let npm run dev bundle my application. It generates a bundle.js perfectly fine when I run webpack, but what appealed to me was having webpack generate a physical file whenever I change something. Gulp and Grunt can do this for me, but I'd like to get it to work with webpack as well.
So, without further ado, some code. I run npm run dev which is defined like so (package.json, just the scripts part*):
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
}
With the following Webpack configuration:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/js/main.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: '/js/bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
contentBase: './dist'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
], ["normal"], "loader")
]
};
Cases:
webpack: Bundles my application into dist/js/bundle.js perfectly fine.
webpack-dev-server: Seems to stream a memory bundle from my JS perfectly fine, but does not generate a bundle on disk.
npm run dev: Starts the webpack server, but does not result in a bundle, nor does my application run, resulting in a Cannot GET/ error.
Can anyone point me in the right direction? I have tried variations on the config, but to no avail.. And just to be complete, I will show my directory structure:
./project
./dist
./js
./bundle.js
./src
./js
./main.js
./package.json
./webpack.config.js
Once again, thanks for the assist!
It is due to wrongly written scripts in package.json file. Replace your scripts with the below. It is because you are not providing the correct path to your bundle.js file which is need to be create. "-p" means to read the entry and output keys of webpack.config.js. Then run this cmd: $ npm run build
"scripts": {
"build": "webpack -p",
"dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
}
For me the problem was with package.json under that "scripts"
Here is the fix:
Inside your package.json file, under script add the following:
"scripts": {
"start": "webpack-dev-server",
"build": "webpack -p"
}
First I ran the build then start.
yarn build
if you first build then your bundle.js file will be created and after that you can use this command:
yarn start
Instead of yarn, you can also use npm
Related
I got the following lines in my package.json file (I just mirrored courses teacher)
"scripts": {
"build:dev": "env NODE_ENV=development webpack --config webpack.config.js",
"build:prod": "env NODE_ENV=production webpack --config webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
But unlike for him it doesn't work for me, when I point my mouse to a build word (both of them), and click "Run Script" I get this error:
Executing task: npm run build:dev
/usr/bin/bash: line 1: npm: command not found
* The terminal process "/usr/bin/bash '-c', 'npm run build:dev'" failed to launch (exit code: 127).
* Terminal will be reused by tasks, press any key to close it.
I certainly see no clues about that issue, and can't find them on the internet.
I have npm installed, and wondering what's wrong. Maybe webpack is bad configured, but If I just run
Webpack
in my console it compiles successfully. Anyway here is my webpack.config.js file:
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const NODE_ENV = process.env.NODE_ENV;
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json']
},
mode: NODE_ENV ? NODE_ENV : 'development',
entry: path.resolve(__dirname, 'src/index.jsx'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
module: {
rules: [{
test: /\.[tj]sx?$/,
use: ['ts-loader']
}]
},
plugins: [
new HTMLWebpackPlugin({ template: path.resolve(__dirname, 'index.html') })
]
};
By the way, I have one problem in my project that may somehow affect mentioned problem (that isn't likely though). I've typed
tsc --init
to create tsconfig.json file and here is vscode problem warning:
`JSON schema for the TypeScript compiler's configuration file
Cannot write file '/home/timothy/Desktop/WEB_COURSE/dist/index.js' because it would overwrite input file.ts
Cannot write file '/home/timothy/Desktop/WEB_COURSE/dist/index.js' because it would overwrite input file.ts`
I didn't try to resolve this issue yet, because I really don't know what even should I do.
My .babelrc config is not working. I keep getting this error message.
Module not found: Can't resolve '#project/customTable' in...
I want to shorten importing paths.
Can someone help me fix this?
Current code: import customTable from "../../../customTable";
Goal: import customTable from "#project/customTable";
Below is my .babelrc file:
{
"plugins": [
["babel-plugin-root-import", {
"rootPathSuffix": "src",
"rootPathPrefix": "#project"
}]
]
}
Use Webpack alias
I'm not sure why your code ain't working. Everything seems to be fine. But, an alternative way would be to do this using Webpack aliases, like so:
modeule.exports = {
entry: [
require.resolve('./polyfills'),
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs
],
resolve: {
alias: {
'#project': path.join(__dirname, '../src') // <--- Here
}
}
}
Q: But, I used create-react-app. I can't find webpack config files in my project directory? :(
A: Run npm run eject and you'll get all the webpack configurations in a config folder of your project directory. :)
Note: Don't forget to restart your application after making all these changes to reflect.
I suppose you are using react-script in your project. You have to know you cant change the Babel config directly. you can use
npm run eject
but it's not a recommended way because by ejecting you'll lose some features like TypeScript, Sass, CSS Modules, and more.
by the way, you can use customize-cra and react-app-rewired npm packages. first, install them:
npm install customize-cra react-app-rewired --dev
//or
yarn add customize-cra react-app-rewired --dev
and create a config-overrides.js file in the same level where your package.json has placed.
and put the below config in it:
const { override, addBabelPlugins } = require("customize-cra");
module.exports = override(
addBabelPlugins([
"babel-plugin-root-import",
{ rootPathSuffix: "./src", rootPathPrefix: "#/" },
])
);
last but not least you have to change all react-script to react-app-rewired in your package.json file like:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
My app is split into an API and a UI portion. Deployment strategy requires they share a package.json. The file structure looks like
client/
src/
main.js
api/
package.json
vue.config.js
I am using the standard vue-cli scripts.
package.json
"scripts": {
"serve:ui": "vue-cli-service serve",
"build:ui": "vue-cli-service build",
"lint:ui": "vue-cli-service lint",
"test:unit": "vue-cli-service test:unit"
}
When I do npm run serve:ui, I get
This relative module was not found:
* ./src/main.js in multi ./node_modules/#vue/cli-service/node_modules/webpack-dev-server/client?http://10.0.2.15:8080/sockjs-node ./node_modules/#vue/cli-service/node_modules/webpack/hot/dev-server.js ./src/main.js
So, I tried modifying vue.config.json as per the docs:
vue.config.js
const path = require('path');
module.exports = {
entry: {
app: './client/src/main.js'
}
}
Now, I get the error:
ERROR Invalid options in vue.config.js: "entry" is not allowed
How do I tell vue-cli where my app entrypoint is?
I discovered based on this Github Issue that you can pass a custom entrypoint only in the command line. This is true for both build and serve. See also in the documentation, a single block of code demonstrating this.
Usage: vue-cli-service serve [options] [entry]
I changed my script to
"serve:ui": "vue-cli-service serve client/src/main.js",
and now it can find the entrypoint.
You can add the entry to the pages option and make sure you include the template too.
vue.config.js
module.exports = {
pages: {
app: {
entry: 'client/src/main.js',
template: 'client/public/index.html',
},
},
};
If you don't like a separate file for this configuration you can also add this to a package.json file:
package.json
"vue": {
"pages": {
"index": {
"entry": "client/src/main.js",
"template": "client/public/index.html"
}
}
},
I believe you are trying to running are building a nodejs app with vue as frontend. I ran into some issues similar to that some time ago and I fixed it by installing laravel-mix to the project which helps me compile vue.
"scripts": {
"start": "node app.js",
"dev": "NODE_ENV=development webpack --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "NODE_ENV=development webpack --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js | nodemon app.js",
"hot": "NODE_ENV=development webpack-dev-server --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"production": "NODE_ENV=production webpack --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js | node app.js"
},
So when i run npm run watch, it run the vue-cli command and power the node app. all in real time.
Create a new file in the root directory named webpack.mix.js
Insert these lines:
let mix = require("laravel-mix");
mix.js("src/js/app.js", "public/js")
.sass('src/scss/app.scss', 'public/css’);
src/js/app.js is the main vue file that compiles to public/css
I'm going to write unit tests in my Symfony project that uses Vuejs for the front-end. I want to use Mocha framework as test runner for my components' tests. So I have configured and installed all things, following this guide: testing vuejs apps
But there's a problem, in my project I'm using Encore, and now I have some troubles to run tests.
I created the setup.js file in this directory of my root's project:
- assets
- js
- components
- test
- setup.js
So I have added in my package.json this config:
"scripts": {
"dev-server": "encore dev-server",
"dev": "encore dev",
"watch": "encore dev --watch",
"build": "encore production",
"compile-translations": "php bin/console bazinga:js-translation:dump public --format=js --merge-domains",
"compile-routes": "php bin/console fos:js-routing:dump --target=public/js/fos_js_routes.js",
"assets-install": "php bin/console assets:install --symlink --relative public",
"test": "cross-env NODE_ENV=test nyc mocha-webpack --webpack-config webpack.config.js --require assets/js/test/setup.js assets/js/test/**/*.spec.js"
},
"nyc": {
"include": [
"assets/js/**/*.(js|vue)"
],
"instrument": false,
"sourceMap": false
},
Now I have a problem, I should add this config in my webpack.config.js file
if (process.env.NODE_ENV === 'test'){
module.exports.externals = [require('webpack-node-externals')()]
module.exports.devtool = 'inline-cheap-module-source-map'
}
But I'm using Encore, so how can I do it?
I resolve the problem using Karma. For anyone that have the same problem, you should following this guide: https://vue-test-utils.vuejs.org/guides/testing-single-file-components-with-karma.html
and then in your karma.conf.js file add these lines at the top:
const Encore = require('#symfony/webpack-encore');
// Initialize Encore before requiring the .config file
Encore.configureRuntimeEnvironment('dev-server');
// Retrieve webpack config
const webpackConfig = require('./webpack.config.js');
The webpack -p cli command fails to uglify es2015 code
package.json
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.13.2",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.13.2"
}
webpack.config.js
var webpack = require("webpack");
var config = {
entry: './src/app.js',
devtool: "source-map",
output: {
path: '../Scripts',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
},
include: ["./src"],
exclude: /node_modules/
}
]
}
}
module.exports = config;
Error when running webpack -p
ERROR in bundle.js from UglifyJs
Unexpected character '`' [./src/LineEndRenderer.js:33,0]
(es2015 template string use)
Running webpack -d works fine.
A user (fulls1z3) at github came up with a solution that does not require babel (see post from 11/26/2016):
Here is a copy:
webpack#2 users, I'm hereby trying to help by providing detailed instructions to use the Harmony branch of UglifyJs2 with webpack:
Fork webpack,
On that fork, delete all branches except master,
Clone master branch to a local folder,
On the local folder, delete all files,
Commit the empty local folder,
Download the latest release (ex: v2.1.0-beta.27 at the moment)
Extract contents of zip file to the local folder,
On the local folder, edit forked package.json, change
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
to point UglifyJs2 (harmony branch) dependency to that branch.
Commit changes,
Finally, point webpack in your package.json to your custom fork:
"webpack": "[USERNAME]/webpack#master"
OR,
Point webpack in your package.json to fulls1z3/webpack (ES6/ES2015 friendly webpack fork):
"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"
I was using webpack globally, so I had to run this too:
npm install yargs supports-color enhanced-resolve interpret tapable webpack-sources source-map uglify-js object-assign async loader-runner acorn watchpack mkdirp ajv ajv-keywords node-libs-browser -g
Then I replaced my global webpack npm folder with webpack-2.1.0-beta.27-harmony.zip from https://github.com/fulls1z3/webpack/releases
Lastly, I replaced my global uglify-js npm folder with UglifyJS2-harmony.zip from https://github.com/mishoo/UglifyJS2/tree/harmony