I just started testing with Jest for the first time. This is a very simple Typescript utils library. I basically followed the installation guide, and my first two tests passed. Yay. The next function I tested imported a few functions from lodash-es, and failed (error below).
This is how I added jest:
pnpm add -D jest ts-jest #types/jest
pnpx ts-jest config:init
My jest.config.js file, as generated by pnpx ts-jest config:init, except that I had to change the second line to export default, because my package.json specifies this to be a module.
/** #type {import('ts-jest').JestConfigWithTsJest} */
export default {
preset: 'ts-jest',
testEnvironment: 'node',
transformIgnorePatterns: [
"node_modules/(?!(lodash-es)/)"
],
moduleNameMapper: {
'lodash-es': '../node_modules/lodash-es/lodash.js',
},
}
I've tried adding transformIgnorePatterns and moduleNameMapper, based on others with similar issues. But no luck.
The error message:
D:\Dev\NodeJs\vexna\packages\util>pnpm test
> #vexna/util#1.0.0 test D:\Dev\NodeJs\vexna\packages\util
> jest
PASS test/reverseString.test.ts
PASS test/hash.test.ts
FAIL test/uid.test.ts
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
D:\Dev\NodeJs\vexna\node_modules\.pnpm\lodash-es#4.17.21\node_modules\lodash-es\lodash.js:10
export { default as add } from './add.js';
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { now, random, padStart, padEnd } from "lodash-es"
| ^
2 | import { reverseString } from "./reverseString"
3 |
4 |
at Runtime.createScriptFromCode (../../node_modules/.pnpm/jest-runtime#29.4.1/node_modules/jest-runtime/build/index.js:1598:14)
at Object.<anonymous> (src/uid.ts:1:1)
at Object.<anonymous> (test/uid.test.ts:1:1)
Test Suites: 1 failed, 2 passed, 3 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 3.494 s
Ran all test suites.
ELIFECYCLE Test failed. See above for more details.
A few things, this project exists in pnpm monorepo, in case it matters.
This is the package.json:
{
"name": "#vexna/util",
"version": "1.0.0",
"description": "Generic utilities, uses lodash",
"private": true,
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"sideEffects": false,
"scripts": {
"build": "rimraf dist && tsc && rollup -c rollup.config.js",
"test": "jest",
"pretest": "npm run build"
},
"devDependencies": {
"#rollup/plugin-typescript": "^11.0.0",
"#types/jest": "^29.4.0",
"#types/lodash-es": "^4.17.6",
"jest": "^29.4.1",
"lodash-es": "^4.17.21",
"rimraf": "^4.1.2",
"rollup": "^3.12.1",
"ts-jest": "^29.0.5",
"typescript": "^4.9.5"
},
"files": [
"dist"
],
"peerDependencies": {
"lodash": "^4.17.21"
}
}
I suspect that perhaps Jest goes off into the boonies because I have externalized lodash?
Or perhaps I should add Babel? But could just as well be something else completely.
Some help is much appreciated!
Use Vitest.
Jest is quite painful to install correctly, whereas Vitest works out of the box without any config. This is my personal experience. It took me days to get Jest to sort-of work. I had Vitest working immediately after installation.
I don't want to hate on Jest, I actually think it's a wonderful and intuitive testing tool. But ultimately Vitest "Just Works" (tm), and you can use the same simple Jest style API we all have come to love.
Steps:
pnpm remove jest ts-jest #types/jest
pnpm add -D vite vitest
Delete jest.config.js, and create vite.config.ts:
/// <reference types="vitest" />
import { defineConfig } from 'vite'
export default defineConfig({
test: {
/* for example, use global to avoid globals imports (describe, test, expect): */
// globals: true,
},
})
Add to your tests:
import { assert, expect, test } from 'vitest'
Update your package.json:
"test": "vitest",
Related
I'm using Vite (vite#3.1.8)
to build Typescript artifacts for an SPA "site" using SolidJS (solid-js#1.6.0).
here's my vite.config.ts
import { defineConfig, resolveBaseUrl } from 'vite'
import solidPlugin from 'vite-plugin-solid'
export default defineConfig({
plugins: [solidPlugin()],
server: {
port: 3000,
},
build: {
target: 'esnext',
outDir: '../htdocs',
rollupOptions: {
input: {
index: "./index.html",
dev: "./dev.html",
test: "./test.ts",
},
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`
}
},
},
});
Currently, it actually builds 2 html files (index.html and dev.html) and the artifacts needed to run those files. Its great. Couldn't be happier.
I would like to have the transpiler to also kick out test.js so that I can run it to do some sanity checking before deploying to production.
I'm hoping to do vite build, and then run node ../htdocs/assets/test.js (or something similar), and have it block the final deployment if any my sanity tests fail.
however, when I attempt to do this, I get an error when I run test.js, complaining about my use of import statements.
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
setting my package type to module in package.json doesn't fix it. changing the test file to test.mjs doesnt fix it. I'm not really sure what to try next.
What I really wish it would do is do the whole "import" as part of transpiling, and make one self-contained test.js that just runs. It seems like that is what it does when it builds index.html and dev.html, why wont it do that for my ts file?
That should work. I just tried making a new repo with your vite.config.ts, one-line index.html, dev.html, and test.ts files, and vite, vite-plugin-solid, solid-js installed. In the end I got a ../htdocs/assets/test.js file.
You might also be interested in checking out Vitest which makes testing like this easier to do, and won't accidentally end up in your deployed htdocs.
The best solution I could find was to make a separate config file for building the tests.
import { defineConfig } from 'vite'
import solidPlugin from 'vite-plugin-solid'
export default defineConfig({
plugins: [solidPlugin()],
server: {
port: 3000,
},
build: {
target: 'esnext',
outDir: '../htdocs',
lib: {
entry: "./test-runner.ts",
name: "test-runner",
fileName: "test-runner"
},
rollupOptions: {
},
},
});
and then, update my package.json to make my test script compile and run the output from that alternative vite config.
"scripts": {
"start": "vite",
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "vite build --config vite.config-tests.ts && node ../htdocs/test-runner.umd.js"
},
When I try to build one of the NextJS apps in my monorepo, I get the error:
$ rm -r packages/library/node_modules/; rm -r packages/daily/node_modules/; rm -r node_modules/; rm -r packages/shared/node_modules; rm package-lock.json; sudo rm -r packages/daily/.next/; npm i; npm --prefix packages/daily/ run build
> next build
info - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
info - Checking validity of types
info - Creating an optimized production build
Failed to compile.
HookWebpackError: processor is not a function
> Build error occurred
Error: > Build failed because of webpack errors
at /home/ubuntu/cal-frontend/packages/daily/node_modules/next/dist/build/index.js:397:19
at async Span.traceAsyncFn (/home/ubuntu/cal-frontend/packages/daily/node_modules/next/dist/telemetry/trace/trace.js:60:20)
at async Object.build [as default] (/home/ubuntu/cal-frontend/packages/daily/node_modules/next/dist/build/index.js:77:25)
The strange thing is that the node/npm version and code are exactly the same as a few days ago when I last ran this command successfully. I have never had this error before. I even tried cloning to a brand new Linux EC2 instance to see if there was some cached file screwing it up but I got exact same error. I am still able to re-deploy the latest commit on Heroku from a few days ago.
The next dev command works fine still.
The issue started happening when I tried to create a new website under packages/ . But the error is persisting even after I reverted to a commit before I made that code.
The monorepo contains two websites that share a package of shared code inside the repo called shared. Here is the webpack next.config.js file for the package/daily app. Again, no code has changed since the error started.
const withFonts = require('next-fonts');
const withTM = require('next-transpile-modules')(['#my-repo-name/shared']);
require('dotenv').config({ path: '../../.env' });
module.exports = withTM(withFonts({
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
webpack(config, options) {
return config;
},
}));
node version: v16.10.0
npm version: 7.24.0
(I also tried building using 16.14 and 8.3, and had the same error)
Also the root level package.json (with personal details redacted):
{
"name": "my-repo-name",
"version": "1.0.0",
"workspaces": {
"packages": [
"packages/*"
]
},
"keywords": [],
"author": "redacted-for-stack-overflow#stackoverflow.org",
"license": "UNLICENSED",
"description": "REDACTED FOR STACK OVERFLOW",
"engines": {
"node": "16.10.0"
},
"cacheDirectories": [
"node_modules",
"packages/library/.next/cache"
],
"scripts": {
"lint": "eslint . --ext js,jsx",
"build": "npm run build --prefix packages/$APP_NAME"
},
"dependencies": {},
"devDependencies": {
"babel-eslint": "^10.1.0",
"eslint": "^7.32.0",
"eslint-config-next": "^11.1.2",
"eslint-plugin-import": "^2.24.2",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.26.1",
"eslint-plugin-react-hooks": "^4.2.0"
}
}
There was an incident yesterday which was causing the issue at Vercel. It should be fixed now.
Adding resolutions keys in package.json solved this for me. Hope this should be a temporary issue with vercel.
"resolutions": {
"cssnano-preset-simple": "3.0.0"
}
Is it possible to test ES6 Modules with Jest without esm or babel? Since node v13 supports es6 natively have tried:
//package.json
{
…
"type": "module"
…
}
//__tests__/a.js
import Foo from '../src/Foo.js';
$ npx jest
Jest encountered an unexpected token
…
Details:
/home/node/xxx/__tests__/a.js:1
import Foo from '../src/Foo.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
When babel is added a transpiler, it works, but can es6 modules be used natively as well?
Yes, it is possible from jest#25.4.0. From this version, there is a native support of esm, so you will not have to transpile your code with babel anymore.
It is not documented yet, but according to this issue you have to do 3 easy steps to achieve that (At the time of writing this answer):
Make sure you don't transform away import statements by setting transform: {} in your jest config file
Run node#^12.16.0 || >=13.2.0 with --experimental-vm-modules flag
Run your test with jest-environment-node or jest-environment-jsdom-sixteen.
So your jest config file should contain at least this:
export default {
testEnvironment: 'jest-environment-node',
transform: {}
...
};
And to set --experimental-vm-modules flag, you will have to run Jest from package.json as follows (I hope this will change in the future):
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}
I hope, this answer was helpful to you.
Note that this is is still experimental, but we have documented how to test this, so there's hopefully less confusion.
https://jestjs.io/docs/en/ecmascript-modules
The steps in https://stackoverflow.com/a/61653104/1850276 are correct
I followed the tips provided in the accepted answer, but I added the property "type": "module" in my package.json in order to jest works properly. This is what I done:
In package.json:
"devDependencies": {
"jest": "^26.1.0",
"jest-environment-jsdom-sixteen": "^1.0.3",
"jest-environment-node": "^26.1.0"
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
},
"type": "module",
"jest": {
"transform": {},
"testEnvironment": "jest-environment-jsdom-sixteen"
}
To run jest from "jest" extension in VSCode with "--experimental-vm-modules" flags, put this config in your global or workspaces settings.json:
"jest.nodeEnv": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
In addition to #Radovan Kuka's answer, here's how to run Jest with ES modules, using npx:
"test:monitoring": "npx --node-arg=--experimental-vm-modules jest -f monitoring.test.js --detectOpenHandles",
The benefit is that one doesn't need to provide the absolute node_modules path.
Without Babel, here's a complete, minimal example that works on recent Jest versions. Run with npm test.
$ tree -I node_modules
.
├── package.json
├── src
│ └── foo.js
└── __tests__
└── foo.spec.js
package.json:
{
"type": "module",
"scripts": {
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
},
"devDependencies": {
"jest": "^29.3.1"
}
}
src/foo.js:
export const bar = () => 42;
__tests__/foo.spec.js:
import {bar} from "../src/foo";
describe("foo.bar()", () => {
it("should return 42", () => {
expect(bar()).toBe(42);
});
});
The secret sauce is in the package.json: "type": "module" and NODE_OPTIONS=--experimental-vm-modules jest.
If you want to add a mock, it's a bit complicated. See this answer.
I wanted to provide a howto on this as I couldn't find any complete information. I thought that this seemed most appropriate in Stackoverflow documentation. However it has been sunsetted *-) - Sunsetting Documentation (*).
Instead I will write this as a StackOverflow Q&A.
How to deploy a Typescript, NodeJS and Express app to Heroku
I created a project (https://gitlab.com/OehmSmith_Examples/herokumovies) that includes a README describing what needs to be done and I will reproduce that here. As a good StackOverflow practice I will also provide a copy of all the code at the bottom of this post.
Tutorial - Deploy Typescript NodeJS Express app to Heroku
This tutorial will work from https://amenallah.com/node-js-typescript-jest-express-starter/ as the base app. I have no affiliation with that site or the author. I chose it as it is simple and works. It is also an example of good OO Typescript code.
Install typescript
Most tutorials or even the official documentation in https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html say to install typescript globally:
> npm install -g typescript
Heroku doesn't have a global install of typescript so it needs to be kept locally. The example project does just this:
> npm i -D nodemon rimraf typescript ts-node ts-jest jest #types/jest #types/node
#types/node
In the case you have pinned your #types/node at an older version you will see something like this error:
~/AppData/Roaming/nvm/v11.15.0/node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6 - error TS2300: Duplicate identifier 'IteratorResult'.
41 type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
~~~~~~~~~~~~~~
node_modules/#types/node/index.d.ts:170:11
170 interface IteratorResult<T> { }
~~~~~~~~~~~~~~
'IteratorResult' was also declared here.
node_modules/#types/node/index.d.ts:170:11 - error TS2300: Duplicate identifier 'IteratorResult'.
170 interface IteratorResult<T> { }
~~~~~~~~~~~~~~
~/AppData/Roaming/nvm/v11.15.0/node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6
41 type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
~~~~~~~~~~~~~~
'IteratorResult' was also declared here.
Found 2 errors.
From TypeScript: Duplicate identifier 'IteratorResult'. And as per that you need to update your version of #types/node. This was a problem I struck as I was working with older code and wanted to include this discussion of it.
Update port for cloud service
Change the index.ts to be the following instead since the original code hard-coded port 5000:
app.listen(process.env.PORT, () => {
console.log(`server started on port ${process.env.PORT}`)
});
To allow for this I have added the PORT to the npm scripts, including adding a start:dev so you can run it like Heroku does from the compiled typescript.
"start:dev": "PORT=5000 node dist/index.js",
"dev": "PORT=5000 nodemon --exec ts-node src/index.ts --watch src",
Or it can be set in a .env file:
PORT=5000
NPM dependencies
Heroku will NOT install dev dependencies (neither will any other cloud provider). Therefore you need to move some dependencies to the main block. For example, a NestJS application has these as Dev Dependencies and they need to be moved:
#nestjs/cli
Dummy data
I added this constructor to the MoviesApi.ts:
constructor() {
// setup some dummy data
movies.push({
name: 'Pirates of the caribbean',
rating: 8.5
})
movies.push({
name: 'Star Wars: A new hope',
rating: 8.7
})
}
Heroku
Now deploy to Heroku
Setup an account if you don't already have one and create an app on Heroku
In your terminal:
heroku login
heroku create moviesheroku // this needs to be unique
You may need to add the returned git url as a remote (check with git remote -v):
git remote add heroku <git url>
Lookup or search for buildpacks with (the next step already specifies those I use):
Lookup at: https://devcenter.heroku.com/articles/buildpacks#officially-supported-buildpacks
Search with:
heroku buildpacks:search typescript
Add buildpacks:
heroku buildpacks:add zidizei/typescript
heroku buildpacks:add heroku/nodejs
Confirm buildpacks:
heroku buildpacks
Commit to your local repository
git init // if not already done
git add --all
git ci -m "Initial commit. Test project all setup and should be ready to 'serve' but not yet ready to deploy to heroku"
Run with
npm dev # OR
npm run start:dev # It depends on your npm scripts
Test with postman or similar or run this from the command-line:
curl http://localhost:5000/movies
Test that it transpiles with npm run build
Update the npm scripts so that after installation (npm install) on Heroku, it will build it before attempting to npm run start
"postinstall": "npm run build" # Depends on your npm scripts
Commit to local repository:
git add --all
git ci -m "Now it should deploy, build and run on heroku"
Deploy to heroku. It should build and start up.
git push heroku master
Test (assuming the app you heroku created is moviesheroku - adjust accordingly)
curl https://moviesheroku.herokuapp.com/movies
Variations
Procfile
I haven't specified a Procfile telling Heroku anything about the app. Fortunately it creates its own defaults by determining that this is a node + npm app. However you can explicitly define this and will need to perform this action if you have multiple apps or similar. You could add a Procfile to contain (this is the default):
web: npm start
Node and NPM version
Heroku also defaults to using one of the most recent versions of these. You could explicitly set the versions at the top-level in the package.json file like:
"engines": {
"node": "10.x",
"npm": "6.x"
},
Although if you don't specify a npm version then Heroku will use a sensible default for the version of node.
Concluding thoughts
I had this going in only a couple hours. The main issues I needed to work out is that typescript has to be local, not global. And the buildpacks. The PORT is an issue also though every cloud provider requires the use of process.env.PORT so this was obvious to me.
Azure was a nightmare and took days, but that was mainly because the workplace I was at insisted on using Windows servers. Long story and I won't go in to it.
AWS was so convoluted. I didn't get the instance I had working after trying for a day. however I do need to try again. The app I was trying used the https://tsed.io/ library. Simple Node / Typescript / Express apps should work out quite easily.
(*) - the sunsetting of documentation was a little bit surprising though given it happened over 2 years ago I guess it wasn't something I used. And I always thought that the Q&A was the easiest place for documentation.
Code
.gitignore
node_modules
dist
coverage
.jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node'
};
package.json
{
"name": "movies",
"version": "1.0.0",
"description": "Example from https://amenallah.com/node-js-typescript-jest-express-starter/ but then modify and / or show steps for how to deploy this Typescript NodeJS Express RESTful app to Heroku.",
"main": "index.js",
"scripts": {
"build": "rimraf dist && tsc",
"postinstall": "npm run build",
"start": "node dist/index.js",
"start:dev": "PORT=5000 node dist/index.js",
"dev": "PORT=5000 nodemon --exec ts-node src/index.ts --watch src",
"test": "jest --watch",
"coverage": "jest --coverage"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#types/express": "^4.17.2",
"#types/jest": "^24.0.25",
"#types/node": "^13.1.2",
"jest": "^24.9.0",
"nodemon": "^2.0.2",
"rimraf": "^3.0.0",
"ts-jest": "^24.2.0",
"ts-node": "^8.5.4",
"typescript": "^3.7.4"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "dist",
"sourceMap": false,
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"paths": {
"*": [
"node_modules/",
],
"typings/*": [
"src/typings/*"
]
},
},
"include": [
"src/**/*.ts"
],
"exclude": [
"src/test/**/*.spec.ts"
]
}
src/api/MoviesApi.ts
import IResource from "typings/IResource";
let movies: object[] = []
export default class MoviesApi implements IResource {
constructor() {
// setup some dummy data
movies.push({
name: 'Pirates of the caribbean',
rating: 8.5
})
movies.push({
name: 'Star Wars: A new hope',
rating: 8.7
})
}
create(data: any): any {
movies.push(data)
return data
}
findMany(): any[] {
return movies;
}
}
src/test/api/Movies.spec.ts
import IResource from '../typings/IResource'
import MoviesApi from '../api/MoviesApi'
const moviesApi: IResource = new MoviesApi()
describe('Movies API', () => {
it('should create a new movie', () => {
const movieData: object = {
name: 'Pirates of the caribbean',
rating: 8.5
};
const movie: object = moviesApi.create(movieData);
expect(movie).toEqual(movieData)
})
});
src/typings/IResource/index.d.ts
export default interface IResource {
create(data: any): any
findMany(): any[]
}
src/index.ts
import * as express from 'express'
import * as bodyParser from 'body-parser'
import MoviesApi from './api/MoviesApi'
const app = express();
const moviesApi = new MoviesApi();
app.use(bodyParser.json());
app.post('/movies', (req: express.Request, res: express.Response) => {
res.json(moviesApi.create(req.body))
});
app.get('/movies', (req: express.Request, res: express.Response) => {
res.json(moviesApi.findMany())
});
app.listen(process.env.PORT, () => {
console.log(`server started on port ${process.env.PORT}`)
});
I have an npm module my_lib that is providing some objects I would like available for use by several downstream modules. my_lib is written in ES6, and uses babel to transpile. It lives in a private github repo accessible to the building hosts of the downstream modules. It is important that the downstream modules consuming my_lib are able to import symbols from my_lib like any other node module.
I would like to be able to write import { libA, libB } from 'my_lib'; in any of the downstream modules and have libA defined as expected by my_lib, assuming that downstream module's package.json includes in dependencies an entry like "my_lib": "orgname/reponame#branchname"
I have an entry in my_lib package.json under scripts like so :
"postinstall" : "npm run build",
"build": "mkdir ./dist && browserify ./src/index.js -t babelify -t envify -o index.js",`
where ./src/index.js is
// Entry point for bundling
export * as libB from "../sublib1/adapter";
export * as libA from "../sublib2/adapter";
If necessary, I could call import {libA, libB} from my_lib/dist/bundle, though this is somewhat undesirable. The main thing is to make all the names I'm exporting from my_lib available in the downstream modules. I'm probably confused about what's going on with browserify and babel. I'm perfectly happy to change the postinstall/build hooks to whatever form is more convenient.
Currently, in the downstream package (an express.js app), I have the line import * as adapters from my_lib; Running npm install on the express app completes without error. I see the index.js file I expect in node_modules/my_lib. When I break in my app after the import (or require for that matter), the adapters object exists, but none of the libB or libA on the object. It seems to be a pure vanilla JS object with no members but __proto__.
Normally in this case i will just use babel and avoid browserify. I use something like this in package.json:
{
"main": "dist/index.js",
"scripts": {
"postinstall": "babel src/ -d dist/"
},
"dependencies": {
"babel-cli": "^6.9.0",
"babel-preset-es2015": "^6.9.0"
}
}
Notice that the main entry point for the package is pointing to dist and not to src. This is to make import my_lib and require('my_lib') (both work well) to use the compiled version of the library.
Additionally this is the content of the .babelrc file that it is side by side with package.json
{
"presets": ["es2015"]
}
I use babel and browserify together.
My package.json
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"build:js": "watchify assets/src/js/main_1.js -o 'exorcist assets/dist/js/main_1.js.map > assets/dist/js/main_1.js' -d -t [babelify --presets [latest]]",
"build:scss": "node-sass -w -r assets/src/scss/ -o assets/dist/css/",
"build": "npm run build:scss & npm run build:js"
},
"devDependencies": {
"babel-cli": "^6.0.0",
"babel-preset-latest": "^6.16.0",
"babelify": "^7.3.0",
"browserify": "^13.1.1",
"exorcist": "^0.4.0",
"node-sass": "^4.5.0",
"watchify": "^3.7.0"
},
"browserify": {
"transform": [
"babelify"
]
}
}
Actual version of package.json: https://gist.github.com/artamonovdev/5f24aaca504e4d1b299bba0413f0a57d